node.js - 在 Node.js 中更改 JPEG 文件 DPI header

标签 node.js phantomjs jpeg puppeteer

我有一个文件(例如 JPEG 大小为 1588 × 2244 像素)。它由 puppeteer 生成(但 phantomjs 也会生成 72 DPI 屏幕截图)。当我将此图像保存到扩展名为 .jpeg 的文件中并使用 macOS General Info 时,我看到:

enter image description here

如您所见,它在元数据中设置了 72 DPI,但我想使用 300 DPI 的文件。我知道,在数字中它不会改变任何东西 - 它是打印的属性,但我不想向每个客户解释这个文件可以 300 DPI 打印。

当我使用 Gimp 和 Image > Print Size

enter image description here

我可以更改 DPI,然后再次导出图片。现在 General Info 窗口中有 300 DPI

enter image description here

我尝试在 Node.JS 服务器上这样做,但我发现很少有选项可以更改 .PNG 图片上的此属性,但任何人都在为 .JPEG 文件工作.

我认为最准确的选择是使用此库中的方法 changeDpiDataUrl: https://github.com/shutterstock/changeDPI/blob/master/src/index.js 但是当我把我的图像作为 base64image 时,在 split 操作之后,我得到了只有 1 个元素的 array - 我认为这是 body,所以我没有格式属性(在 63 行)。

有人遇到过这个问题吗?

最佳答案

您可以使用图书馆 piexifjs更改图像的 EXIF 数据。该库仅更改元数据(称为 EXIF),而不更改图像本身。

代码示例

以下代码使用 API读取图像的 EXIF 数据,对其进行更改并根据更改后的数据创建新缓冲区。

const piexif = require("piexifjs");

// get the image buffer from puppeteer or from disk
const imageBuffer = /* ... */

// convert buffer to string and load it
const imageString = imageBuffer.toString('binary');
const exif = piexif.load(imageString);

// change resolution
exif['0th'][piexif.ImageIFD.XResolution] = [300,1];
exif['0th'][piexif.ImageIFD.YResolution] = [300,1];

// generate new EXIF data
const newExifDump = piexif.dump(exif);

// generate new image
const newData = piexif.insert(newExifDump, imageString);
const jpgBuffer = new Buffer(newData, "binary");

// write to file or use buffer
// ...

请注意,我自己没有使用过该库,也没有测试过代码。

关于node.js - 在 Node.js 中更改 JPEG 文件 DPI header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57843481/

相关文章:

node.js - TravisCI 失败,无法启动 PhantomJS

node.js - WebdriverJS/IO 和 PhantomJS - 具有属性选择器的点击处理程序不适用于 PhantomJS

node.js - Express 用户未定义

Node.js Cookie 解析器停止加载页面

javascript - 如何用PhantomJS动态抓取 "changing"数据?

ios - UIimagejperepresentation 压缩质量与其他算法的比较

python - 使用 fpdf 将 jpg 添加到 pdf

windows - 一个类似ImageOptim的windows图像压缩工具(of mac)

node.js - 无法将sqlite3编译为本地插件,Electron React Boilerplate项目

javascript - 错误 : There was an error loading firebase. json : Bolt not installed, 运行 npm install -g firebase-bolt