How to convert filetype using GraphicsMagick for node.js - node.js

How do you "Convert" a file from one type to another using gm? (e.g .png > .jpg)
I found this but it doesn't seem that the node.js version has the same method:

You'll need to change the format of the output file.
var writeStream = fs.createWriteStream("output.jpg");
gm("img.png").setFormat("jpg").write(writeStream, function(error){
console.log("Finished saving", error);
});
http://aheckmann.github.io/gm/docs.html#setformat

Related

pipe file directly from file system

I'm using "express": "^4.13.3" on node 6.9.0
When i try to pipe data a jpeg image:
const path = config.storageRoot + '/' + req.params.originalFileName;
var mimetype = mime.lookup(req.params.originalFileName);
res.writeHead(200, { 'Content-Type': mimetype});
fs.createReadStream(path).pipe(res);
i get xml data inside the result:
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.5-c014 79.151739, 2013/04/03-12:12:15 ">
When i use res.end with the result from a fs.readFile instead, the binary content is formatted correctly.
What am i doing wrong?
Take a look how I'm piping files in the examples in this answer:
How to serve an image using nodejs
It's something like this:
// 'type' is the MIME type
var s = fs.createReadStream(file);
s.on('open', function () {
res.set('Content-Type', type);
s.pipe(res);
});
s.on('error', function () {
res.set('Content-Type', 'text/plain');
res.status(404).end('Not found');
});
So I'm just setting the header to be posted by Express instead of posting the headers explicitly. Also I'm handling the stream events. Maybe you should try doing it similarly because the way I did it seems to work, according to Travis:
https://travis-ci.org/rsp/node-static-http-servers
Another thing in addition to handling the stream events and errors would be to make sure that you have the correct encoding, permissions etc. I don't know what result are you expecting and what that XML means or where it comes from, but handling the stream events may tell you more about what is happening.

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

Node writeFileSync encoding options for images

I'm using fs.writeFileSync(file, data[, options]) to save a file returned from http.get(options[, callback])
This works fine for text files but images, pdfs etc end up being corrupted. From the searching around that I've done, it's apparently because fs.writeFileSync(file, data[, options]) defaults to UTF-8
I've tried setting the encoding to 'binary', the mime-type and the extension to no avail. It feels like something really obvious that I'm overlooking, can anyone point me in the right direction?
Thank you in advance
Update
I'm running this through electron. I didn't think it was worth mentioning as electron is just running node, but I'm not a node or electron expert so I'm not sure
Create a Buffer from the image data and set its encoding to binary. Then pass that data into a stream.PassThrough and pipe that into a stream.Writable.
var fs = require('fs');
var stream = require('stream');
var imgStream = new stream.PassThrough();
imgStream.end(Buffer.from(data, 'binary'));
var wStream = fs.createWriteStream('./<dest>.<ext>');
imgStream.once('end', () => {
console.log('Image Written');
});
imgStream.once('error', (err) => {
console.log(err);
});
imgStream.pipe(wStream);

JPEG File Encoding and writeFile in Node JS

I'm using http.request to download JPEG file. I am then using fs.writeFile to try to write the JPEG file out to the hard drive.
None of my JPEG files can be opened, they all show an error (but they do have a file size). I have tried all of the different encodings with fs.writeFile.
What am I messing up in this process?
Here's what the working one is showing when viewing it raw:
And here is what the bad one using fs.writeFile is showing:
Figured it out, needed to use res.setEncoding('binary'); on my http.request.
Thank you, looking to the previous response, I was able to save de media correctly:
fs.writeFile(
filepath + fileName + extension,
mediaReceived, // to use with writeFile
{ encoding: "binary" }, // to use with writeFile ***************WORKING
(err) => {
if (err) {
console.log("An error ocurred while writing the media file.");
return console.log(err);
}
}
);

NodeJS: Asynchronous file read problems

New to NodeJS.
Yes I know I could use a framework, but I want to get a good grok on it before delving into the myriad of fine fine tools that are out there.
my problem:
var img = fs.readFileSync(path);
the above works;
fs.readFile(path, function (err, data)
{
if (err) throw err;
console.log(data);
});
the above doesn't work;
the input path is : 'C:\NodeSite\chrome.jpg'
oh and working on Windows 7.
any help would be much appreciated.
Fixed
Late night/morning programming, introduces errors that are hard to spot. The path was being set from two different places, and so the source path were different in both cases. Thankyou for your help. I am a complete numpty. :)
If you are not setting an encoding when reading a file, you will get the binary content.
So for example, the following snippet will output the content of the test file using UTF-8 encoding. If you don't use an encoding, you will get an output like "" on your console (raw binary buffer).
var fs = require('fs');
var path = "C:\\tmp\\testfile.txt";
fs.readFile(path, 'utf8', function (err, data) {
if (err) throw err;
console.log(data);
});
Another issue (especially on windows-based OS's) can be the correct escaping of the target path. The above example shows how path's on Windows have to be escaped.
java guys will just use this javascript asynchronous command as if in pure java , troublefreely :
var fs = require('fs');
var Contenu = fs.readFileSync( fILE_FULL_Name , 'utf8');
console.log( Contenu );
That should take care of small & big files.

Resources