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

Viewed 7707

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?

4 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)
    })
  })
}

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

Related