如何保存重新编码的数据?

问题描述

我想将接收到的重新编码的数据保存到另一个文件中,以便可以将其解码回去。

但是现在我想将jpg图像编码为相同的jpg格式,而无需更改ascii代码

因此,即使通过编码传递并单独保存,我也希望获得相同的图像。

这是我的代码

static constexpr int64_t ascii_encoding[] {
    0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255
};


std::filesystem::path filename = "test.jpg";
std::ifstream in(filename,std::ios::binary);


for (unsigned char c; in.get((char&)c);) {

    std::cout << (int)ascii_encoding[c] << " | " << c << " | " << (int)c << std::endl
}

还必须将数据存储在255上方以进行进一步解码。 例如,我可以将ASCII码104更改为777并保存。

解决方法

因此,我不清楚您为什么清楚地拥有文件输入操作后却无法弄清楚文件输出操作。但是无论如何这是代码

std::ifstream in("test.jpg",std::ios::binary);
std::ofstream out("test.jpg.out",std::ios::binary);
for (unsigned char c; in.get((char&)c);) {
    std::cout << (int)ascii_encoding[c] << " | " << c << " | " << (int)c << std::endl;
    out.put((char)ascii_encoding[c]);
}

就是这样。一行代码打开输出文件,一行代码输出编码值。

编辑

似乎您想将int64_t值输出到文件中。可以做到如下

    out.write((char*)&ascii_encoding[c],sizeof ascii_encoding[c]);

请注意,此代码是特定于平台的,如果在一个平台上使用此代码,则可能难以在另一个平台上读回代码。

,

在处理二进制文件时,我发现freadfwrite更加直观。 下面的代码接收一个png文件(格式无关紧要。您可以删除扩展名,并且仍然可以使用。)并制作一个副本。

如果原始数据没有超出您说的255个限制,则此代码将根本不会修改副本。

尽管可以更好地处理TOTALbuf_size

#include <iostream>
#include <fstream>
#include <cstdio>
#include <vector>

const int TOTAL = 58393 * 4;
// Keep buffer a multiple of TOTAL.
const int buf_size = TOTAL / 4;
const std::string infilepath = "png.png";
const std::string outfilepath = "pngcopy.png";

#define FOR_ALL_OF_THEM for (int i = 0; i < TOTAL; ++i)

void read_bin(std::vector<int> &all_of_them)
{
  FILE *infile = fopen(infilepath.c_str(),"rb");
  FOR_ALL_OF_THEM
  {
    fread(&all_of_them[i],sizeof(int),buf_size,infile);
    i += buf_size - 1;
  }
}

void write_bin(const std::vector<int> &all_of_them)
{
  FILE *outfile = fopen(outfilepath.c_str(),"wb");
  FOR_ALL_OF_THEM
  {
    fwrite(&all_of_them[i],outfile);
    i += buf_size - 1;
  }
  fclose(outfile);
}

int main()
{
  std::vector<int> all_of_them(TOTAL);
  read_bin(all_of_them);
  write_bin(all_of_them);
}