如何在Node.js中将二进制缓冲区保存到PNG文件? [英] How to save binary buffer to png file in nodejs?
问题描述
我有二进制的nodejs Buffer对象,其中包含位图信息。如何从缓冲区制作图像并将其保存到文件?
I have binary nodejs Buffer object that contains bitmap information. How do make image from the buffer and save it to file?
编辑:
我尝试使用文件系统软件包,如@herchu所说,但如果我这样做:
I tried using the file system package as @herchu said but if I do this:
let robot = require("robotjs")
let fs = require('fs')
let size = 200
let img = robot.screen.capture(0, 0, size, size)
let path = 'myfile.png'
let buffer = img.image
fs.open(path, 'w', function (err, fd) {
if (err) {
// Something wrong creating the file
}
fs.write(fd, buffer, 0, buffer.length, null, function (err) {
// Something wrong writing contents!
})
})
我得到
推荐答案
注意:我正在根据您最近的修改来编辑我的答案
如果您使用的是Robotjs,请检查其位图对象包含用于原始像素数据的缓冲区-不是PNG或任何其他文件格式的内容,只是彼此相邻的像素(在您的情况下为200 x 200元素)。
If you are using Robotjs, check that its Bitmap object contains a Buffer to raw pixels data -- not a PNG or any other file format contents, just pixels next to each other (exactly 200 x 200 elements in your case).
我没有在Robotjs库中找到任何以其他格式写入内容的函数(也不是我也知道),因此在此答案中,我使用的是另一个库 Jimp ,用于图像处理。
I have not found any function to write contents in other format in the Robotjs library (not that I know it either), so in this answer I am using a different library, Jimp, for the image manipulation.
let robot = require("robotjs")
let fs = require('fs')
let Jimp = require('jimp')
let size = 200
let rimg = robot.screen.capture(0, 0, size, size)
let path = 'myfile.png'
// Create a new blank image, same size as Robotjs' one
let jimg = new Jimp(size, size);
for (var x=0; x<size; x++) {
for (var y=0; y<size; y++) {
// hex is a string, rrggbb format
var hex = rimg.colorAt(x, y);
// Jimp expects an Int, with RGBA data,
// so add FF as 'full opaque' to RGB color
var num = parseInt(hex+"ff", 16)
// Set pixel manually
jimg.setPixelColor(num, x, y);
}
}
jimg.write(path)
注意通过手动遍历所有像素来完成转换;这在JS中很慢。另外,还有关于每个库如何处理其像素格式的一些详细信息,因此循环中需要进行一些操作-从嵌入的注释中应该很清楚。
Note that the conversion is done by manually iterating through all pixels; this is slow in JS. Also there are some details on how each library handles their pixel format, so some manipulation was needed in the loop -- it should be clear from the embedded comments.
这篇关于如何在Node.js中将二进制缓冲区保存到PNG文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!