[英]Read binary code of image to write it into a different file
I made an encryption tool for encoding texts and txt files.我制作了一个用于编码文本和 txt 文件的加密工具。 The tool gets 8 bit binary code of input char then encrypts it with other functions for ex:
该工具获取输入字符的 8 位二进制代码,然后使用其他函数对其进行加密,例如:
a.txt file has: a.txt 文件有:
xxyz xxyz
reader = fs.createReadStream('./a.txt', {
flag: 'r',
encoding: 'UTF-8',
highWaterMark: 1
})
reader.on('data', function (chunk) {
console.log( chunk + " --> " + toBin(chunk) )
//writer.write( toStr(reverse(toBin(chunk))) );
});
////////////// TRANSLATORS //////////////
function toBin(text)
return (
Array
.from(text)
.reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
.map(bin => '0'.repeat(8 - bin.length) + bin )
.join('')
);
}
function toStr(bin) {
return String.fromCharCode(parseInt(bin, 2))
}
OUTPUT: OUTPUT:
x --> 01111000
x --> 01111000
y --> 01111001
z --> 01111010
--> 00001010
The last one is EOL, I think.最后一个是EOL,我想。 To encrypt this I basically use my functions like:
为了加密这个,我基本上使用我的函数,比如:
function swap(bin) {
return bin.slice(4, 8) + bin.slice(0, 4)
}
function reverse(bin) {
return bin.split("").reverse().join("")
}
Then these functions works well for txt files.然后这些函数适用于 txt 文件。 I can decrypt and encrypt.
我可以解密和加密。
When I try the same way on a png file for ex, there is a problem:当我在 ex 的 png 文件上尝试相同的方法时,出现了问题:
console.log( chunk + " --> " + toStr(toBin(chunk)) )
writer.write( toStr(toBin(chunk)) );
/* OUT
® --> ®
B --> B
` --> `
-->
*/
That looks nice when we look the output, but when we try to open the file it created and not empty it says:当我们查看 output 时,这看起来不错,但是当我们尝试打开它创建的文件而不是清空文件时,它会说:
"Couldn't load image, unrecognized image file format. “无法加载图像,无法识别的图像文件格式。
When I try to open image with text editor:当我尝试使用文本编辑器打开图像时:
Original png image原始png图像
Just used string to binary, binary to string, wrote to new file.
只是使用字符串到二进制,二进制到字符串,写入新文件。
As you can see, they are not same.如您所见,它们并不相同。 I think I shouldn't read it like reading a text file.
我认为我不应该像阅读文本文件那样阅读它。 So how should I read it?
那我应该怎么读呢?
NOTE: Tried more tobin functions but that's the most true one because some of them were saying range error because of reading a big file than txt files, some of them were giving 7 bit codes, and some of them was giving 000 or undefined sometimes.注意:尝试了更多的 tobin 函数,但这是最真实的一个,因为其中一些函数由于读取比 txt 文件大的文件而说范围错误,其中一些给出 7 位代码,而其中一些给出 000 或未定义有时。
Thanks.谢谢。
I think it is about how you write the image file.我认为这与您如何编写图像文件有关。 I hope this helps.
我希望这有帮助。
You need write it as: buffer or binary您需要将其写为:缓冲区或二进制
// in this states data must be as binary
fs.writeFile("file.png", data, "binary", cb)
// other case you can write with streams
fs.createWriteStream("file.png", {
encoding: "binary"
})
writer.write(chunks);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.