首页 > 解决方案 > Save Image into a file in C++

问题描述

I want to save an image into a custom file, in order to secure all images of my program.

I tried to save every pixels (as Uint32) of an image like this (I am using SFML)

void fromPNGtoCustomFile(sf::Texture texture, std::string path)
{
    std::ofstream fo; 
    fo.open(path);

    sf::Image image=texture.copyToImage(); //GET IMAGE OF THE TEXTURE

    fo << image.getSize().x << " " << image.getSize().y << " "; // WRITE THE SIZE OF THE IMAGE

    for(unsigned int i=0; i< image.getSize().x; i++)
    {
        for(unsigned int j=0; j< image.getSize().y; j++)
        {
            fo << image.getPixel(i, j).toInteger() << " "; 

            // image.getPixel(x, y).toInteger() RETURNS A Uint32 VALUE
        }
    }


    fo.close();
}

Then I load image from the file using the same logic.

It worked, but I realised that the size of the file I created was around 250 Mb, when my original .png image was only 8 Mb. If I compress the new file using 7Zip, I get a 8 Mb file, as the original size. I do not understand why I get this size.

I don't really know what is the best way to create custom file for saving images.

Do you have any suggestions, or correction of my code?

标签: c++imagefilesavesfml

解决方案


要回答为什么文件大小如此之大的问题,这是因为您正在独立编写每个像素的信息,因此您的文件最终会尽可能大。为了减小尺寸,压缩格式利用了例如通常存在大量相同颜色的相邻像素的事实。例如,天空图像很可能包含大量相同蓝色阴影的像素。因此,您需要做的是使用某种特殊代码定义一个算法,以表示“接下来的 N 个像素是某种 RGB 颜色”或类似的东西。

关于图像数据压缩的一个很好的来源是 DSP 指南的这一章:http ://www.dspguide.com/ch27.htm


推荐阅读