如何在JavaScript中设置JPEG/PNG图像中的分辨率/密度



我需要在JavaScript中更改JPG/PNG类型的图像类型的分辨率/密度。我需要这样做的原因是,我可以将图像发送到第三方API,然后知道根据分辨率/密度元数据打印每英寸多少像素(DPI/PPI)。

JavaScript中是否有任何这样的解决方案?

对于任何对解决方案的好奇的人,我最终使用GraphicMagic(Node的Image Magick的版本)。因为我使用的是AWS lambda(其实例是由ImageMagic预装的),所以它使它变得更容易,我只需要安装'gm'npm包。

这不是最性能的解决方案,因为我必须在重新采样后调整大小,但是它有效!

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

您也可以使用这个最近发布的库,该库完全仅对JPEG(JFIF)和PNGS进行DPI操作

https://github.com/shutterstock/changedpi

您可以通过添加/更改PNG文件的物理块来做到这一点:

您可以在https://github.com/murkle/rewrite-png-phys-chunk上查看我的代码,以了解更多

可以使用JavaScript标准图像处理可以轻松设置分辨率/密度,该图像处理通过使用Mettadata功能。

简单示例:

// Set output metadata to 96 DPI
const data = await sharp(input)
  .withMetadata({ density: 96 })
  .toBuffer();

NPM模块:敏锐

最新更新