Reading image into char array
Hi All.
I need to read an image to char array with C++. I have written the following code for it, but it seems that the code does not read the entire image, it just reads the part of it. Can someone hint why, or give some better solution for how to read an image into char array?
std::fstream image;
image.open("C:\\bbb.bmp");
image.seekg (0, ios::end);
int n = image.tellg();
image.seekg (0, ios::beg);
char* res = new char[n];
image.read(res, n);
Thanks behorehand.
Re: Reading image into char array
Quote:
Originally Posted by
loolyn
Hi All.
I need to read an image to char array with C++. I have written the following code for it, but it seems that the code does not read the entire image, it just reads the part of it. Can someone hint why, or give some better solution for how to read an image into char array?
First of all, you should open the file in binary mode and not text mode, since the file is an image file.
More than likely, because you opened the file in text mode, the EOF character was reached, and the text mode handling kicked in and stopped the file read.
Regards,
Paul McKenzie
Re: Reading image into char array
Thanks for the reply Paul.
I modified the code to be like this:
std::fstream image;
image.open("C:\\bbb.bmp", std::ios_base::binary);
image.seekg (0, ios::end);
int n = image.tellg();
image.seekg (0, ios::beg);
char* res = new char[n];
for(int i = 0; i < n; i++)
res[i] = '5';
bool bit = image.eof();
image.read(res, n);
But now another issue arose. I don't know why the value of "n" becomes "-1".
Re: Reading image into char array
Try one of the following:
1) use ifstream instead of fstream
2) add ios::in to the open mode
Re: Reading image into char array
I used ifstream instead of fstream, and that worked.
Thanks a lot.
Re: Reading image into char array
Quote:
Originally Posted by
loolyn
Hi All.
I need to read an image to char array with C++. I have written the following code for it, but it seems that the code does not read the entire image, it just reads the part of it. Can someone hint why, or give some better solution for how to read an image into char array?
std::fstream image;
image.open("C:\\bbb.bmp");
image.seekg (0, ios::end);
int n = image.tellg();
image.seekg (0, ios::beg);
char* res = new char[n];
image.read(res, n);
Thanks behorehand.
Use unsigned char if you're reading in full bytes.