繁体   English   中英

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

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

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

javascript中有没有这样的解决方案?

对于任何对解决方案感到好奇的人,我最终使用了graphicMagic(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 ) 和 PNG 进行 dpi 操作

https://github.com/shutterstock/changeDPI

您可以通过添加/更改 PNG 文件的 pHYs 块来完成此操作:

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

分辨率/密度可以很容易地使用JavaScript标准图像处理liberary设置尖锐通过为metadata功能。

简单的例子:

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

npm 模块: sharp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM