writeFile写入二进制数据以创建图像文件

writeFile写入二进制数据以创建图像文件

本文介绍了使用node.js fs.writeFile写入二进制数据以创建图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用node.js fs.writeFile 编写画布数据作为二进制文件. JPEG文件,但是在写入文件后,我可以看到该文件存储为纯文本格式,而不是二进制数据.

I'm trying to write a canvas data with node.js fs.writeFile as a binary. JPEG file, but after the file is written I can see that the file is stored as plain text, not binary data.

这是从客户端发送到我的节点的data的示例,代表JPEG图像数据(仅几个开头字符):

This is an example of the data sent from the client to my node, representing the JPEG image data (just a few first characters):

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAFA3PEY8MlBGQUZaVVBfeM...

我通过执行以下操作在客户端获得data :

I'm getting this data on the client side by performing:

canvas.toDataURL('image/jpeg', 0.5).replace('data:image/jpeg;base64,', '')

这是我的 node.js服务器中的功能用法:

Here is the function usage in my node.js server:

fs.writeFile('../some.jpeg', data, 'binary', function(err){});

它不是将文件写入二进制文件(״״ JFIF ...),而是完全写入从客户端接收到的数据.

Instead of the file being written as binary (״״ JFIF ...), it writes exactly the data it received from the client.

我在做什么错了?

推荐答案

虽然纯JavaScript可以处理Unicode编码的字符串,但不能很好地处理直接的二进制数据.

Pure JavaScript, while great with Unicode encoded strings, does not handle straight binary data very well.

将大量数据写入套接字时,以二进制格式存储数据要比从Unicode转换效率更高.

When writing large amounts of data to a socket it's much more efficient to have that data in binary format vs having to convert from Unicode.

var fs = require('fs');
// string generated by canvas.toDataURL()
var img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0"
    + "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO"
    + "3gAAAABJRU5ErkJggg==";
// strip off the data: url prefix to get just the base64-encoded bytes
var data = img.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile('image.png', buf);

参考

这篇关于使用node.js fs.writeFile写入二进制数据以创建图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 20:51