I need to change the resolution/density in JPG/PNG type of images in javascript. The reason I need to do this is so that I can send the image to a third party API which will then know how many pixels per inch (DPI/PPI) to print based on the resolution/density metadata.
Are there any such solution in javascript?
For anyone curious on a solution, I ended up using graphicMagic (node's version of Image Magick). Because I am using AWS Lambda (whose instances comes preinstalled with ImageMagic), it made it easier, I just had to install 'gm' npm package.
It isn't the most performant solution because I have to resize after resample, but it works!
const gm = require('gm').subClass({imageMagick: true});
function addResolution(inputBuffer, resizeWidth, resizeHeight) {
return new Promise((resolve, reject) =>{
gm(inputBuffer)
.resample(150, 150) // resampled to 150 resolution
// you have to set the width and height again because resample rearranges those params
.resize(resizeWidth, resizeHeight, '!')
.toBuffer('JPEG',function (err, buffer) {
if (err) reject(err)
resolve(buffer)
})
})
}
You can also use this recently published library, that does exactly just dpi manipulation for JPEG ( JFIF ) and PNGs
You can do this by adding/changing the pHYs chunk of a PNG file:
You can check my code at https://github.com/murkle/rewrite-png-pHYs-chunk to understand more
The resolution/density can be set easily using JavasCript standard image processing liberary sharp by withMetadata function.
Simple example:
// Set output metadata to 96 DPI
const data = await sharp(input)
.withMetadata({ density: 96 })
.toBuffer();
Npm module: sharp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.