trying to access and manipulate images with node.js and GD or imagemagick - node.js

i'm trying to create a thumbnail of an jpg that resides on the server. i tried using node-gd and/or node-imagemagick but neither could access the file:
var gd = require('node-gd');
gd.openJpeg("./test.jpeg", function (img, path) {
if (img) {
console.log("file opened ... " + img);
}
else {
console.log("failed to open file ...");
}
});
logs: failed to open file ...
imagemagick:
var im = require('imagemagick');
im.identify('./test.jpeg', function (err, features) {
if (err) throw err;
console.log(features);
});
logs: Error: Command failed: execvp(): No such file or directory
but the test.jpeg file is definitely there.
var fs = require('fs');
fs.open(filePath, 'r', function (err, fd) {
console.log("open file ... " + err + " " + fd);
});
works fine!? no error is logged.
i tried chmod 0777 on the jpeg. nothing.

From what I understand of the documentation of the imagemagick module for node is, that the module provides access to the comandline binaries of imagemagick. Do you have imagemagick (the commandline binaries) installed? Are they in the PATH of you shell?
You are looking for a binary named "identify". You can show the path to it by running "which identify". It should give you a full path - if the prompt just returns, you don't have it installed or it's not in your path.
If you are on win32 the which command won't help, you have to check for a binary called identify.exe.
(never worked with gd - so I am unsure there)
here is the imagemagick example with your code - please note, the path to identify may be different in your environment:
snowflake:Desktop rhaen$ node check_im.js
{ format: 'JPEG', width: 320, height: 250, depth: 8 }
snowflake:Desktop rhaen$ which identify
/usr/local/bin/identify
So - the node module and your code works for me.

Related

electron app.getpath('exe') result is not what I expected

I want to start my app automatically on system startup.
I used auto-launch.
var AutoLaunch = require('auto-launch');
var autoLauncher = new AutoLaunch({
name: "App name",
path: app.getPath('exe'),
});
console.log(`app path : ${app.getPath('exe')}`)
//result : C:\Users\USER-PC\project_folder\dist\electron.exe
autoLauncher.isEnabled().then(function(isEnabled) {
if (isEnabled) return;
autoLauncher.enable();
}).catch(function (err) {
throw err;
});
The problem is, I am using electron-builder for building an exe file. And when I build an exe file its name is like : 'app-name 1.0.0.exe'.
So auto launch is not working properly because the option, 'path' is different from the actual exe file's path.
How can I solve this?
I tried to set the app name so app.getPath('exe') can return the actual .exe path. But it did not work.
app.setName('app-name')

Switch to what ever path is input nodejs

Lets assume you have installed an electron app and you are asked to input the path to your current project. You might do something like: ~/Documents/projectName.
How do I, in node take that input and check if it exists, specifically if you entered in the path as shown above?
the reason for this is that I want to see if A) the path exists and B) if theres a specific file there (I'll be using path.join(dirEntered, fileName.extension).
Is there a way to do what I want? I see chdir but that changes where the working directory is. which I guess would be fine but doing:
process.chdir('~/Documents') Shows: no such file or directory, uv_chdir(…)
I want to avoid having the user to enter the full absolute path of their project. That seems "bad to me". And uploading their project isn't necessary, Im reading a single file (so theres no need for upload here).
Any ideas?
Is it possible to tap into the cli commands and take this input feed it there and get the result? Or is that over kill?
Here's an idea how to solve it. If the path starts with a tilde, it replaces that tilde with the full home directory of the current user. It then uses fs.stat to see if the given path actually exists.
const fs = require("fs");
const os = require("os");
var path = "~/Documents";
if (path.indexOf("~") === 0) {
path = os.homedir() + path.substring(1);
}
fs.stat(path, (err, stats) => {
if (!err) {
// document or path exists
if (stats.isFile()) {
console.log("Path " + path + " is a file");
} else if (stats.isDirectory()) {
console.log("Path " + path + " is a directory");
}
} else {
// document or path does not exist
}
});

Tiff convert to png Node js

i have to convert multiple tiff to png. For example tiff which include 3 pages i should convert to 3 png's.So i am using tiff-to-png module and i have encountered with this problem.
Error: Command failed: convert /tiffs/one.tiff -scene 1 ./png/one/page%d.png
Invalid Parameter - /tiffs.Bellow is my code
'use strict'
const tiff_to_png=require('tiff-to-png');
const options={
logLevel:1
};
const converter=new tiff_to_png(options);
const tiffsLocation=['./tiffs/one.tiff'];
const location='./png';
converter.convertArray(tiffsLocation,location);
In the error context we see -/tiffs inavliiad parameter.
tiffsLocation is the variable which conatin my tiff file.
location is variable which contain path to folder where will be converted png file.
I cant understand why i have goten this error, tiffs in this case is the directory which contain my tiff file why i have got this error.Any ideas?
1st You have to install "Imagemagick"
For windows, you will find .exe file. Keep it in your mind that on installation time, check "Install legacy utilities (e.g: convert)"
For Ubuntu:
sudo apt install imagemagick
For Cent OS:
sudo yum install ImageMagick
var fs=require('fs');
var spawn = require('child_process').spawn;
//ifile: Tiff Absolute File Path
//ofile: PNG Absolute File Path (e.g: var ofile = APP_ROOT_PATH+'/data/files/png/sample.png';)
var tiff2png = spawn('convert', [ifile, ofile]);
tiff2png.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
tiff2png.stderr.on('data', function (data) {
return res.json(Utility.output('Unable to convert tiff to png','ERROR'));
console.log('stderr: ' + data);
});
tiff2png.on('close', function (code) {
/**Check Your Converted file exist or not. If exist then Converted**/
console.log('Close: ' + data);
});
tiff2png.on('error', function (code) {
return res.json(Utility.output('ERROR: Unable to convert tiff to png','ERROR'));
});
I found 2 libraries that do this:
https://github.com/oliver-moran/jimp
https://github.com/lovell/sharp
In the end I went with sharp as jimp could not handle 16bit images

reading a packaged file in aws lambda package

I have a very simple node lambda function which reads the contents of packaged file in it. I upload the code as zip file. The directory structure is as follows.
index.js
readme.txt
Then have in my index.js file:
fs.readFile('/var/task/readme.txt', function (err, data) {
if (err) throw err;
});
I keep getting the following error NOENT: no such file or directory, open '/var/task/readme.txt'.
I tried ./readme.txt also.
What am I missing ?
Try this, it works for me:
'use strict'
let fs = require("fs");
let path = require("path");
exports.handler = (event, context, callback) => {
// To debug your problem
console.log(path.resolve("./readme.txt"));
// Solution is to use absolute path using `__dirname`
fs.readFile(__dirname +'/readme.txt', function (err, data) {
if (err) throw err;
});
};
to debug why your code is not working, add below link in your handler
console.log(path.resolve("./readme.txt"));
On AWS Lambda node process might be running from some other folder and it looks for readme.txt file from that folder as you have provided relative path, solution is to use absolute path.
What worked for me was the comment by Vadorrequest to use process.env.LAMBDA_TASK_ROOT. I wrote a function to get a template file in a /templates directory when I'm running it locally on my machine with __dirname or with the process.env.LAMBDA_TASK_ROOT variable when running on Lambda:
function loadTemplateFile(templateName) {
const fileName = `./templates/${templateName}`
let resolved
if (process.env.LAMBDA_TASK_ROOT) {
resolved = path.resolve(process.env.LAMBDA_TASK_ROOT, fileName)
} else {
resolved = path.resolve(__dirname, fileName)
}
console.log(`Loading template at: ${resolved}`)
try {
const data = fs.readFileSync(resolved, 'utf8')
return data
} catch (error) {
const message = `Could not load template at: ${resolved}, error: ${JSON.stringify(error, null, 2)}`
console.error(message)
throw new Error(message)
}
}
This is an oldish question but comes up first when attempting to sort out whats going on with file paths on Lambda.
Additional Steps for Serverless Framework
For anyone using Serverless framework to deploy (which probably uses webpack to build) you will also need to add the following to your webpack config file (just after target: node):
// assume target: 'node', is here
node: {
__dirname: false,
},
Without this piece using __dirname with Serverless will STILL not get you the desired absolute directory path.
I went through this using serverless framework and it really was the file that was not sent in the compression. Just add the following line in serverless.yml:
package:
individually: false
include:
- src/**
const filepath = path.resolve('../../filename.text');
const fileData2 = fs.readFileSync(process.env.LAMBDA_TASK_ROOT + filepath, 'utf-8');
I was using fs.promises.readFile(). Couldn't get it to error out at out. The file was there, and LAMBDA_TASK_ROOT seemed right to me as well. After I changed to fs.readFileSync(), it worked.
I hade the same problem and I tried applying all these wonderful solutions above - which didn't work.
The problem was that I setup one of the folder name with one letter in upper case which was really lowercase.
So when I tried to fetch the content of /src/SOmething/some_file.txt
While the folder was really /src/Something/ - I got this error...
Windows (local environment) is case insensitive while AWS is not!!!....

Resizing images using imagemagick in node.js

In my application i tried to resize the image using imagemagick but i got following error error while resizing: imagesexecvp(): No such file or directory.this is my code
im.resize({
srcPath: '/tmp/Images/' + req.files.image.name,
dstPath: 'resized_'+req.files.image.name ,
width:42,
height:42
}, function(err, stdout, stderr){
if (err) {
console.log('error while resizing images' + stderr);
};
});
The imagemagick module uses the convert and identify commands and the error you describe could happen because the commands can't be found. Make sure the commands are in a folder referenced by the path environment variable or, alternatively you can reference the commands in you node application:
var im = require('imagemagick');
im.identify.path = '/opt/ImageMagick/bin/identify'
im.convert.path = '/opt/ImageMagick/bin/convert';
It looks like you are trying to resize the file without changing the destination. Try this:
im.resize({
srcPath: process.cwd() + '/tmp/Images/' + req.files.image.name,
dstPath: process.cwd() + '/tmp/Images/resized_'+req.files.image.name ,
width:42,
height:42
}, function(err, stdout, stderr){
if (err) {
console.log('error while resizing images' + stderr);
};
console.log( process.cwd() + '/tmp/Images/' + req.files.image.name + 'has been resized and saved as ' + process.cwd() + '/tmp/Images/resized_'+req.files.image.name)
});
You might also check your permissions (ls -l) in /tmp/Images/ to make sure they are set properly
You need to install image magic command line tools. Try brew install imagemagick
If you are on ubuntu, install package like this:
apt-get install imagemagick
After that, try again :D

Resources