在node.js中:如何将jpg图像转换为二进制数据?

5

相反地,我如何将二进制数据转换回图像?因为后端保存的图像数据是以二进制形式存储的。


图片已经是二进制格式了。您还期望进行什么其他转换? - CuriousMind
3个回答

15

试试这个。

var fs = require("fs");

fs.readFile('image.jpg', function(err, data) {
  if (err) throw err;

  // Encode to base64
  var encodedImage = new Buffer(data, 'binary').toString('base64');

  // Decode from base64
  var decodedImage = new Buffer(encodedImage, 'base64').toString('binary');
});

希望对你有用。


1

1
如果您想要一个读取文件(当然,您也可以读取图像)并将其转换为二进制的解决方案,我在NodeJS中编写了一小段代码,希望它能帮助到您。这只涉及将文件读入二进制,但您肯定可以将字符串转换为数组或字节数组。如果您卡在这里,请在下面的评论中让我知道。
以下是一个简单而健壮的代码片段,您可以尝试使用。
 params format:
 getBinary({
   path : '<file_relative_path>',
   padlength: '<prepending_padding_length>', (Default: 4)
   debug: false,                             (Default: true)
   limit: 10                                 (Default: Full_File_Length)
   putSpacing: Boolean                       (Default: false)
 })

 Params Description:
   1. path: Specifies the relative file path, to be read.
   2. padlength: After reading the file, it reads object as number 
                 (ex: hex(f): 1111, hex(0): 0), so if you need a 
                 uniform length binary string then you will need to 
                 fill the strings. as hex(0): 0000 when padlength is 4.
   3. limit: limits the read buffer to render.
   4. putSpacing: if true it puts a space after each padlength.


or
getBinary('<file_relative_path>');

在这里获取: https://computopedia.com/how-to-convert-image-to-binary-nodejs/

要点: https://gist.github.com/shankha96/cffe620776066078289ea1f8b15956e0


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接