【问题标题】:C++ how to create a PNG file with known data?C ++如何使用已知数据创建PNG文件?
【发布时间】:2014-08-07 15:12:33
【问题描述】:

只是想知道,如果我将 PNG 文件作为二进制文件读取,并且我知道如何将十六进制数字写入另一个纯 txt 或任何文件,那么如何使用这些十六进制数字重新创建 PNG 文件?

这是我用来从 PNG 文件读取并写入另一个纯 txt 文件的代码:

unsigned char x;
ifile.open("foo.png",ios::binary);
ifile>>noskipws>>hex;
while(ifile>>x){
  ofile<<setw(2)<<setfill('0')<<(int)x;
  //do some formatting stuff to the ofile, ofile declaration omitted
  //some ifs to see if IEND is read in, which is definitely correct
  //if IEND, break, so the last four hex numbers in ofile are 49 45 4E 44
}
//read another 4 bytes and write to ofile, which are AE 42 60 82, the check sum

我这样做的原因是因为我有一些PNG文件在IEND块之后有一些不相关的消息,我想摆脱它们,只保留与实际图片相关的块并将它们分成不同的文件. “无关信息”是指它们不是图片的实际部分,但我对它们还有其他用途。

【问题讨论】:

  • 这个问题似乎是基于错误的假设,即二进制文件(例如 png)与人类可读的十六进制数字列表相同。
  • 这段代码按预期工作,它输出一个纯文本文件,其中包含 PNG 文件的十六进制数字。我有一个十六进制阅读器,我可以确认它正在输出正确的东西。我只是不知道如何将它们放在一起制作PNG文件。 @DrewDormann
  • 只需反转操作即可。读入两个字符,然后转换为二进制。
  • 您的意思是将 0 位和 1 位作为二进制文件写入文件吗?@CaptainObvlious
  • 你应该和cat讨论这个问题。

标签: c++ png


【解决方案1】:

这很简单,您只需读取每 2 个字符并将它们从十六进制转换回二进制。

unsigned char x;
char buf[3] = {0};
ifile.open("foo.hex");
while(ifile>>buf[0]>>buf[1]){
    char *end;
    x = (unsigned char) strtol(buf, &end, 16);
    if (*end == 0) // no conversion error
        // output the byte

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2018-01-18
    • 2012-06-05
    • 1970-01-01
    • 2021-03-26
    • 2015-03-03
    相关资源
    最近更新 更多