Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a resolution/density in JPEG/PNG image in Javascript?

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?

like image 523
andre Avatar asked Jan 03 '23 09:01

andre


2 Answers

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)
    })
  })
}
like image 161
andre Avatar answered Jan 05 '23 21:01

andre


You can also use this recently published library, that does exactly just dpi manipulation for JPEG ( JFIF ) and PNGs

https://github.com/shutterstock/changeDPI

like image 22
AndreaBogazzi Avatar answered Jan 05 '23 22:01

AndreaBogazzi