I am trying to resize image in node.js by this program .
https://github.com/LearnBoost/node-canvas/blob/master/examples/resize.js
var Canvas = require('canvas')
, Image = Canvas.Image
, fs = require('fs');
var img = new Image
, start = new Date;
img.src = __dirname + 'flowers.jpg';
console.log('Resized and saved in %dms');
img.onload = function(){
console.log('Resized and saved in buffer');
try{
var width = img.width / 2
, height = img.height / 2
, canvas = new Canvas(width, height)
, ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
canvas.toBuffer(function(err, buf){
console.log('Resized and saved in buffer');
fs.writeFile(__dirname + '/resize.jpg', buf, function(){
console.log('Resized and saved in %dms', new Date - start);
});
});
}catch(e){
console.log(sys.inspect(e));
}
};
img.onerror = function(err){
throw err;
};
the program is not going in the onload function why ?
Edit :
give this error while trying img.src after attaching the onload and onerror events?
`Resized and saved in NaNms
/home/reach121/rahul/knox/index.js:33
throw err;
^
Error: error while reading from input stream
at Object.<anonymous> (/home/reach121/rahul/knox/index.js:35:9)
at Module._compile (module.js:404:26)
at Object..js (module.js:410:10)
at Module.load (module.js:336:31)
at Function._load (module.js:297:12)
at Array.0 (module.js:423:10)
at EventEmitter._tickCallback (node.js:170:26)
Using Image Magic giving me this error :
reach121#youngib:~/rahul/knox$ sudo node index.js
node.js:178
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Command failed: execvp(): No such file or directory
at ChildProcess.<anonymous> (/usr/local/lib/node/.npm/imagemagick/0.1.2/package/imagemagick.js:64:15)
at ChildProcess.emit (events.js:67:17)
at Socket.<anonymous> (child_process.js:172:12)
at Socket.emit (events.js:64:17)
at Array.<anonymous> (net.js:826:12)
at EventEmitter._tickCallback (node.js:170:26)
Code :
var im = require('imagemagick');
im.resize({
srcPath: __dirname + '/flowers.jpg',
dstPath: __dirname + '/flowers-small.jpg',
width: '50%'
}, function(err, stdout, stderr){
if (err) throw err
console.log('resized')
});
Have you already tried setting img.src after attaching the onload and onerror events? Just noticed this as a difference between the original example and yours.
Another question: is the onerror event triggered? If so, the thrown exception could be helpful.
Update
If you just want to resize images and don't need to use any canvas-specific operations, simply use ImageMagick and node-imagemagick. I just did a small test and it worked out of the box:
var im = require('imagemagick');
im.resize({
srcPath: __dirname + '/koala.jpg',
dstPath: __dirname + '/koala-small.jpg',
width: '50%'
}, function(err, stdout, stderr){
if (err) throw err
console.log('resized')
});
For the node_imagemagick module to work you need to install the imagemagick CLI interfaces,
On a mac it can be as easy as:
brew install imagemagick
But this really depends on your specific system.
__dirname does not have a trailing slash.
Change it to this:
img.src = __dirname + '/flowers.jpg';
And attach event handlers before setting img.src like #schaermu said.
FYI, your console.log statement uses a %d but there's no variable after the quoted string. (I'm not sure this solves your other errors.)
Related
I am running into a problem with my cordova app where after an app update, localStorage is cleared. I am now attempting to save some basic user data to a text file instead, using cordova's FileWriter and FileReader.
At some point cordova updated and these methods and now requires a plugin to read and write files: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html
Because my live iOS application uses the old version of cordova, it must write with FileWriter. My app update (not live) uses a newer version of cordova and therefore must use the plugin.
------ Possible workaround found, see update below ------
When trying to read the file, I am seeing the following error in xcode:
017-01-26 17:58:52.990 MyApp[40355:2892997] ERROR: Method 'hello there' not defined in Plugin 'File'
2017-01-26 17:58:52.991 MyApp[40355:2892997] -[CDVCommandQueue executePending] [Line 142] FAILED pluginJSON = ["File1875336264","File","hello there",["cdvfile://localhost/persistent/player_data.txt",null,null]]
Note: I'm running the following code in Safari console while the iOS simulator is running, just for convenience
My code for writing the file
(function() {
var onFail = function(err) {
alert('write action failed!');
alert(err.code);
};
var onGotFS = function(fileSystem) {
alert( 'gotFS' );
fileSystem.root.getFile("player_data.txt", {create: true}, onGotFileEntry, onFail);
};
var onGotFileEntry = function(fileEntry) {
alert( 'gotFileEntry, path: ' + fileEntry.fullPath );
fileEntry.createWriter(onGotFileWriter, onFail);
};
var onGotFileWriter = function(writer) {
alert( 'gotFileWriter' );
writer.onwrite = onFileWritten;
writer.onerror = onFail;
var data = "hello there";
alert( 'writing data: ' + data );
writer.write( data );
};
var onFileWritten = function(evt) {
alert( "saveTokenToFile SUCCESS!" );
};
// start process of looking up file system and writing
alert( 'requesting file system ...' );
window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024, onGotFS, onFail);
})();
My code for reading the file:
(function() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
fs.root.getFile("player_data.txt", { create: true }, function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
alert("Success");
console.log(evt.target.result);
};
reader.onerror = function() {
console.log("reader error");
};
reader.readAsText(file);
}, onErrorReadFile);
});
}, onErrorLoadFs);
var onErrorReadFile = function(){
console.log("error reading file");
}
var onErrorLoadFs = function() {
console.log("request file system has failed to load.");
}
})();
UPDATE
In case anyone else runs into this, I did find a way to read the saved file. The fileEntry object has a URL path to the saved file. To access the data on the file, I'm passing that URL to jQuery.getJSON, which gives us back some readable json.
readDataFromFile: function(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
fs.root.getFile("player_data.txt", {}, function (fileEntry) {
var entryURL = fileEntry.nativeURL;
jQuery.getJSON(entryURL, function(data) {
console.log(data);
}).fail(function(){
console.log("file found, but contents were empty");
});
}, onErrorGetFile);
}, onErrorLoadFs);
var onErrorLoadFs = function() {
console.log("request file system has failed to load.");
};
var onErrorGetFile = function() {
console.log("requested file can not be read or does not exist");
};
}
I have read lots of things about this subjet but i can't find a complete documentation.
I succeeded to use electron-packager and electron-winstaller to get a setup.exe for my electron application.
I used electron-release-server to create a server to host my electron app to deploy.
I add in my electron app this peace of code
const autoUpdater = electron.autoUpdater;
var feedUrl = 'http://10.61.32.53:1337//download/:' + app.getVersion();
autoUpdater.setFeedURL(feedUrl);
// event handling after download new release
autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
// confirm install or not to user
var index = dialog.showMessageBox(mainWindow, {
type: 'info',
buttons: [i18n.__('Restart'), i18n.__('Later')],
title: "Typetalk",
message: i18n.__('The new version has been downloaded. Please restart the application to apply the updates.'),
detail: releaseName + "\n\n" + releaseNotes
});
if (index === 1) {
return;
}
// restart app, then update will be applied
quitAndUpdate();
} );
But when i install my application, i have this error :
In fact, i think i don't understand what to do client side but server side as well. Any help would be very appreciated !
Thanks in advance
I used following in my version and that works (except the Tray Icon):
app.on('ready', () => {
console.warn("Starting Autoupdater")
console.warn(app.getVersion())
var feedUrl = 'http://ls-desktop.herokuapp.com/update/' + os.platform() + '/' + app.getVersion() + '/';
autoUpdater.setFeedURL(feedUrl);
tray = new Tray(__dirname + '/LS.png')
console.log(__dirname + '/LS.png')
console.log('created');
autoUpdater.on('checking-for-update', function() {
tray.displayBalloon({
title: 'Autoupdater',
content: 'Checking for Update!'
})
});
autoUpdater.on('update-available', function() {
console.log("update-available");
});
autoUpdater.on('update-not-available', function() {
tray.displayBalloon({
title: 'Autoupdater',
content: 'No Updates availible!'
})
});
autoUpdater.on('update-downloaded', function() {
console.log(" update-downloaded");
});
setTimeout(function() {autoUpdater.checkForUpdates()}, 10000);
autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
var index = dialog.showMessageBox({
type: 'info',
buttons: ['Restart', 'Later'],
title: "Lornsenschule Vertretungsplan",
message: ('The new version has been downloaded. Please restart the application to apply the updates.'),
detail: releaseName + "\n\n" + releaseNotes
});
if (index === 1) {
return;
}
quitAndUpdate()
});
})
Note the setTimeout(function() {autoUpdater.checkForUpdates()}, 10000); that is the real workaround that I used. the rest is just an nice Addition I think
I have an app built in Ionic Framework, and the backend of this app has a Rails app administrator panel, with content editor, user control, image uploads (using Carrierwave).
I made a API that returns the concise information to Ionic app. And isolates the Rails admin panel in a private network.
I get fully posts contents, relations from the another objects, and sends to Ionic app via JSON.
But I don't how properly deals with uploaded (via Carrierwave) assets to show the images in my Ionic app.
Thanks,
then first you have to add 3 plugins which are below
cordova plugin add org.apache.cordova.file-transfer
cordova plugin add org.apache.cordova.file
cordova plugin add org.apache.cordova.camera
And copy below code and pest into your controller to pick image from
gallery and upload on server
$scope.editProfileImgGallary = function() {
navigator.camera.getPicture(uploadEditProfilePhotosImage, onFailEditProfilePhoto, {
targetWidth: 512,
targetHeight: 512,
quality: 40,
correctOrientation: true,
allowEdit: true,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
});
}
function onFailEditProfilePhoto(message) {
// alert('Failed because: ' + message);
}
function uploadEditProfilePhotosImage(imageURI) {
// $ionicLoading.show({
// template: '<p>Loading...</p><ion-spinner icon="bubbles"></ion-spinner>'
// });
console.log(imageURI);
// var img = document.getElementById('userEditProfileImg');
// img.src = imageURI;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI('uploadimg.php'), winEditProfilePhotos, failEditProfilePhotos, options);
}
function winEditProfilePhotos(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
// $ionicLoading.hide();
}
function failEditProfilePhotos(error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
// $ionicLoading.hide();
// var alertPopup = $ionicPopup.alert({
// title: 'Uh Oh!',
// template: 'You Get Some Error Please Try Again..'
// });
}
And copy bellow code and pest into your HTML page onClick Event
<div ng-click="editProfileImgGallary();" ></div>
Using phonegap build for iOS platform, the download procedure is not working!
Could someone tell me why the code below returned errors messages:
("download error source " + error.source);
could not download the image from online
// e.g: http://www.sushikoapp.com/img/branches/thumbs/big_sushiko-bchamoun.jpg
("upload error code" + error.code); sometimes 1 and sometimes 3
The code is below:
var ios_directoryEntry = fileSystem.root;
ios_directoryEntry.getDirectory("branches", { create: true, exclusive: false }, onDirectorySuccessiOS, onDirectoryFailiOS);
var ios_rootdir = fileSystem.root;
//var ios_fp = ios_rootdir.fullPath;
var ios_fp = ios_rootdir.toURL();
ios_fp = ios_fp + "branches/" ;
//ios_fp = "cdvfile://localhost/persistent/branches/";
var fileTransfer = new FileTransfer();
fileTransfer.download(encodeURI(imgURL + "branches/thumbs/big_sushiko-bchamoun.jpg" ), ios_fp + "big_big_sushiko-bchamoun.jpg",
function (entry) {
alert("download complete: " + entry.fullPath);
}
},
function (error) {
//Download abort errors or download failed errors
alert("download error source " + error.source);
alert("upload error code" + error.code);
}
);
Thank you for your suggestion...
The problem is you're treating the file API operations as synchronous, when they're actually asynchronous.
You can use cordova.file to reference the target folder on the filesystem (see here: https://github.com/apache/cordova-plugin-file/blob/master/doc/index.md).
So try something like this:
resolveLocalFileSystemURL(cordova.file.documentsDirectory, onGetDocuments, function(error) {
console.error("Error getting Documents directory: "+error.code);
});
function onGetDocuments(entry) {
console.log("Got Documents directory");
entry.getDirectory("branches", { create: true, exclusive: false }, onGetBranches, function(error) {
console.error("Error creating/getting branches directory: "+error.code);
});
}
function onGetBranches(entry){
console.log("Got branches directory");
doFileTransfer(entry.toURL());
}
function doFileTransfer(ios_fp){
var fileTransfer = new FileTransfer();
fileTransfer.download(encodeURI(imgURL + "branches/thumbs/big_sushiko-bchamoun.jpg" ), ios_fp + "big_big_sushiko-bchamoun.jpg",
function (entry) {
alert("download complete: " + entry.fullPath);
}
},
function (error) {
//Download abort errors or download failed errors
alert("download error source " + error.source);
alert("upload error code" + error.code);
}
);
}
You are trying to write a file to the iOS root File system, this is not possible since all app in iOS are sandboxed and can only access their own sandbox.
So don't use fileSystem.root but fileSystem.documents.
i am developing a phonegap project in mac os with xcode. in xcode if i create a cordova based application it automatically creates cordova-1.6.0.js. i am using fileupload plugin for sending svg file to my server. in fileupload.js i have written alert fileuplaoder function as following,
var FileUploader = function() {
alert("gi");
}
this alert is working, but when i give the aler under upload function,
FileUploader.prototype.upload = function(server, file, params, fileKey, fileName, mimeType, success, fail, progress) {
alert("upload");
this._doUpload('upload', server, file, params, fileKey, fileName, mimeType, success, fail, progress);
};
this alert is not working. my call for this plugin in html page is,
window.plugins.fileUploader.upload('http:192.168.1.54:8080/downloadFiles', '/Users/User/Library/Application Support/iPhone Simulator/5.0/Applications/408DBBC7-67F7-4E8B-B41C-663CDC0377B5/Documents/image5_1.jpg.txt.svg', {foo: 'bar'}, 'myPhoto', 'image5_1.jpg.txt.svg', 'image/svg',
function(result) {
console.log('Done: ' + result);
},
function(result) {
console.log("Error: " + result);
},
function(loaded, total) {
var percent = 100 / total * loaded;
console.log('Uploaded ' + percent);
}
);
in fileupload.js there is cordova.addConstructor method. but in my generated cordova.1.6.0.js file there is no such method. i dont know whats happening. pl help me to work this plugin.
i found the solution. there is a upload and download options in the cordova file api itself. its working fine. the code is,
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("image5_2.jpg.svg", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
var localpath=fileEntry.fullPath;
uploadPhoto(localpath);
//fileEntry.createWriter(gotFileWriter, fail);
}
function uploadPhoto(imageURI) {
alert(imageURI);
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName="image5_2.jpg.svg";
options.mimeType="image/svg+xml";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://192.168.1.54:8080/POC/fileUploader", win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
pl use this.