繁体   English   中英

如何将JPEG图像加载到char数组C ++中?

[英]How to load an JPEG image into a char array C++?

我想将JPEG图像存储到普通的无符号char数组中,我曾使用ifstream来存储它; 但是,当我检查存储的数组是否正确时(通过将其再次重写为JPEG图像),使用存储的数组重写的图像无法正确显示,因此我认为问题一定会出现从我用来将图像存储到数组中的技术来看是不正确的。 我想要一个可以完美存储的数组,以便可以再次使用它重写为JPEG图像。如果有人可以帮助我解决此问题,我将非常感谢!

int size = 921600;
    unsigned char output[size];
    int i = 0;

    ifstream DataFile;
    DataFile.open("abc.jpeg");
    while(!DataFile.eof()){
        DataFile >> output[i];
        i++;
    }
    /* i try to rewrite the above array into a new image here */
    FILE * image2;
    image2 = fopen("def.jpeg", "w");
    fwrite(output,1,921600, image2);
    fclose(image2);

显示的代码中存在多个问题。

while(!DataFile.eof()){

始终是一个错误 请参阅链接的问题以获取详细说明。

    DataFile >> output[i];

按照定义,格式化的提取运算符>>跳过所有空白字符并忽略它们。 您的jpg文件肯定在其中的某个位置有字节0x09、0x20和其他几个字节,这会自动跳过并且不读取它们。

为了正确执行此操作,您需要使用read()和gcount()来读取二进制文件。 正确使用gcount()还应该使您的代码正确检测文件结束条件。

确保在打开文件时添加错误检查。 找到文件大小,然后根据文件大小读入缓冲区。

您可能还会考虑使用std::vector<unsigned char>进行字符存储。

int main()
{
    std::ifstream DataFile("abc.jpeg", std::ios::binary);
    if(!DataFile.good())
        return 0;

    DataFile.seekg(0, std::ios::end);
    size_t filesize = (int)DataFile.tellg();
    DataFile.seekg(0);

    unsigned char output[filesize];
    //or std::vector
    //or unsigned char *output = new unsigned char[filesize];
    if(DataFile.read((char*)output, filesize))
    {
        std::ofstream fout("def.jpeg", std::ios::binary);
        if(!fout.good())
            return 0;
        fout.write((char*)output, filesize);
    }

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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