繁体   English   中英

读取图像的二进制代码以将其写入不同的文件

[英]Read binary code of image to write it into a different file

我制作了一个用于编码文本和 txt 文件的加密工具。 该工具获取输入字符的 8 位二进制代码,然后使用其他函数对其进行加密,例如:

a.txt 文件有:
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:

x --> 01111000
x --> 01111000
y --> 01111001
z --> 01111010

 --> 00001010

最后一个是EOL,我想。 为了加密这个,我基本上使用我的函数,比如:

function swap(bin) {
    return bin.slice(4, 8) + bin.slice(0, 4)
}
function reverse(bin) {
    return bin.split("").reverse().join("")
}

然后这些函数适用于 txt 文件。 我可以解密和加密。
当我在 ex 的 png 文件上尝试相同的方法时,出现了问题:

console.log( chunk + " --> " + toStr(toBin(chunk)) )
writer.write( toStr(toBin(chunk)) );
/* OUT
® --> ®
B --> B
` --> `
 --> 
*/

当我们查看 output 时,这看起来不错,但是当我们尝试打开它创建的文件而不是清空文件时,它会说:
“无法加载图像,无法识别的图像文件格式。
当我尝试使用文本编辑器打开图像时:
原始png图像在此处输入图像描述 只是使用字符串到二进制,二进制到字符串,写入新文件。 在此处输入图像描述

如您所见,它们并不相同。 我认为我不应该像阅读文本文件那样阅读它。 那我应该怎么读呢?
注意:尝试了更多的 tobin 函数,但这是最真实的一个,因为其中一些函数由于读取比 txt 文件大的文件而说范围错误,其中一些给出 7 位代码,而其中一些给出 000 或未定义有时。
谢谢。

我认为这与您如何编写图像文件有关。 我希望这有帮助。

您需要将其写为:缓冲区或二进制

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM