I need a way to use Node.js to convert a photo from HEIC format to either jpg or png. I have searched and cannot seem to find anything that works.
Node.js convert HEIC file
Asked Answered
If you can use a browser environment, take a look at github.com/alexcorvi/heic2any. npmjs.com/package/cloudmersive-image-api-client is a service which provides the same but for a price (free tier available at 1000 calls/5mb limit at the moment tho) –
Preferable
npm -i heic-convert
const convert = require('heic-convert');
async function heicToPng(file, output) {
console.log(file, output);
const inputBuffer = await promisify(fs.readFile)(file);
const outputBuffer = convert({
buffer: inputBuffer, // the HEIC file buffer
format: 'PNG', // output format
});
return promisify(fs.writeFile)(output, outputBuffer);
}
Your function name is heicToJpg but format passed to convert fn is png. You may want to change that. –
Cook
With heic-convert as Bruno suggested, it works fine. Here is a node utility that allows you to serially convert HEIC files present in a folder: convert-heic-files
Here Use base64 encode string example:
const convert = require("heic-convert");
base64Data='data:image/heic;base64,............';
const base64Data = data.split(",")[1];
const heicBuffer = Buffer.from(base64Data, "base64");
const { buffer } = await convert({
buffer: heicBuffer, // HEIC buffer
format: "PNG", // Output format
});
const pngBase64 = Buffer.from(buffer).toString("base64");
const pngDataUrl = `data:image/png;base64,${pngBase64}`;
If you need utility that can quickly and efficiently handle conversion and resizing of high resolution HEIC images to JPEG or PNG then I'd suggest you try Scaler service.
import Scaler from 'scaler.pics';
const scaler = new Scaler('YOUR_API_KEY');
const { outputImage } = await scaler.transform({
input: { localPath: '/path/to/large-image.heic' },
output: {
type: 'jpeg',
fit: { width: 1500, height: 1500 },
quality: 0.8,
},
});
Other nodejs tools like heic-convert
or sharp
can bring your server to a halt and it takes long time to convert even just one high resolution image.
Changing the filename is sufficient for viewing HEIC as jpg:
const fileName = photo.fileName.split(".")[0] + ".jpg";
Oh god no! Please don't do this. It's not sufficient at all. You might be lucky that your viewer could handle this. But it's not possible to work with such file. Any other program might report this as a corrupted file. –
Hamulus
this has been working great for over a year now! –
Hemoglobin
@BrandonB It's working because images (and other file types often) have a type encoded in the first few bytes. Your image reader is using that data to determine the file type (not the file extension). –
Subscapular
wow how is this the accepted answer. It doesn't change the format at all. –
Acrocarpous
© 2022 - 2024 — McMap. All rights reserved.