c++ - 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?
解决方案
要回答为什么文件大小如此之大的问题,这是因为您正在独立编写每个像素的信息,因此您的文件最终会尽可能大。为了减小尺寸,压缩格式利用了例如通常存在大量相同颜色的相邻像素的事实。例如,天空图像很可能包含大量相同蓝色阴影的像素。因此,您需要做的是使用某种特殊代码定义一个算法,以表示“接下来的 N 个像素是某种 RGB 颜色”或类似的东西。
关于图像数据压缩的一个很好的来源是 DSP 指南的这一章:http ://www.dspguide.com/ch27.htm
推荐阅读
- c - C中的静态成员
- assembly - 如何比较 x86-64 中的两个寄存器
- ms-access - MS Access VBA - 将字符串附加到文本框,更新时重新附加
- microsoft-teams - MS Teams 活动(通过 API 完成)未显示在 Teams 报告中的原因是什么?
- google-play-services - 使用 Google 表格更改多个帐户的共享广告系列预算的 Bing Ads 脚本
- r - 如何获取特定元素的列和行索引(数字)?
- python-3.x - 熊猫在列中保留一个字符串,其中一些值为日期时间,但其他不是日期时间?
- r - 过滤至少有两个模式匹配的地方
- tsql - 通过整理成带有分隔数据的单列,将两个带有分隔数据的 sql 列组合起来
- ramda.js - 使用 ramdajs 将记录数组转换为摘要或透视