简体   繁体   English

读写图像数据C ++

[英]Read and write image data C++

I've just started learning C++, and I'm working on a program that is supposed to grab an image from the hard disk and then save it as another name. 我刚刚开始学习C ++,我正在研究一个应该从硬盘中获取图像然后将其保存为另一个名称的程序。 The original image should still remain. 原始图像仍应保留。 I've got it work with text files, because with those I can just do like this: 我已经使用了文本文件,因为我可以这样做:

ifstream fin("C:\\test.txt");
ofstream fout("C:\\new.txt");

char ch;
while(!fin.eof())
{
    fin.get(ch);
    fout.put(ch);
}

fin.close();
fout.close();
}

But I suppose that it's not like this with images. 但我想这与图像不一样。 Do I have to install a lib or something like that to get it work? 我是否必须安装lib或类似的东西才能使它工作? Or can I "just" use the included libraries? 或者我可以“只”使用附带的库? I know I'm not really an expert of C++ so please tell me if I'm totally wrong. 我知道我不是C ++的专家所以请告诉我,如果我完全错了。

I hope someone can and want to help me! 我希望有人可以并且想帮助我! Thanks in advance! 提前致谢!

Btw, the image is a .png format. 顺便说一下,图像是.png格式。

You can use the std streams but use the ios::binary argument when you open the stream. 您可以使用std流,但在打开流时使用ios :: binary参数。 It's well documented and there is several examples around the internet 它有很好的文档记录,互联网上有几个例子

You are apparently using MS Windows: Windows distinguishes between "text" and "binary" files by different handling of line separators. 您显然正在使用MS Windows:Windows通过不同的行分隔符处理来区分“文本”和“二进制”文件。 For a binary file, you do not want it to translate \\n\\r to \\n on reading. 对于二进制文件,您不希望它在读取时将\\n\\r\\n To prevent it, using the ios::binary mode when opening the file, as @Emil tells you . 为了防止它,在打开文件时使用ios :: binary模式,正如@Emil告诉你的那样

BTW, you do not have to use \\\\ in paths under windows. 顺便说一下,你不必在windows下的路径中使用\\\\ Just use forward slashes: 只需使用正斜杠:

ifstream fin("C:/test.txt");

This worked even back in WWII using MS-DOS. 这甚至可以在二战中使用MS-DOS。

If the goal is just to copy a file then CopyFile is probably better choice than doing it manually. 如果目标只是复制文件,那么CopyFile可能是比手动操作更好的选择。

#include <Windows.h>
// ...
BOOL const copySuccess = CopyFile("source.png", "dest.png", failIfExists);
// TODO: handle errors.

If using Windows API is not an option, then copying a file one char at a time like you have done is very inefficient way of doing this. 如果使用Windows API不是一个选项,那么像您一样一次复制一个文件的文件是非常低效的方法。 As others have noted, you need to open files as binary to avoid I/O messing with line endings. 正如其他人所说,你需要打开文件作为二进制文件,以避免I / O搞乱行结尾。 A simpler and more efficient way than one char at a time is this: 这比一次更简单,更有效的方式是:

#include <fstream>
// ...
std::ifstream fin("source.png", std::ios::binary);
std::ofstream fout("dest.png", std::ios::binary);
// TODO: handle errors.
fout << fin.rdbuf();

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

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