【问题标题】:Read binary code of image to write it into a different file读取图像的二进制代码以将其写入不同的文件
【发布时间】:2020-08-09 01:15:06
【问题描述】:

我制作了一个用于编码文本和 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))
}

输出:

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
` --> `
 --> 
*/

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

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

【问题讨论】:

    标签: node.js binary


    【解决方案1】:

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

    你需要写成:缓冲区或二进制

    // 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多