我需要在javascript中更改JPG/PNG类型的图像的分辨率/密度。我需要这样做的原因是,我可以将图像发送到第三方API,该API将根据分辨率/密度元数据知道每英寸多少像素(DPI/PPI)进行打印。
是否有任何javascript解决方案?
我需要在javascript中更改JPG/PNG类型的图像的分辨率/密度。我需要这样做的原因是,我可以将图像发送到第三方API,该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)
})
})
}
@AndriyKulak
- fmw42您可以通过添加/更改PNG文件的pHYs块来实现此操作:
您可以查看我的代码https://github.com/murkle/rewrite-png-pHYs-chunk以了解更多信息。
分辨率/密度可以使用JavaScript标准图像处理库sharp的withMetadata函数轻松设置。
简单示例:
// Set output metadata to 96 DPI
const data = await sharp(input)
.withMetadata({ density: 96 })
.toBuffer();
Npm模块:sharp