-
June 10th, 2010, 07:03 AM
#1
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.
-
June 10th, 2010, 07:08 AM
#2
Re: Reading image into char array
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
-
June 10th, 2010, 07:29 AM
#3
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".
-
June 10th, 2010, 07:49 AM
#4
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
-
June 10th, 2010, 08:00 AM
#5
Re: Reading image into char array
I used ifstream instead of fstream, and that worked.
Thanks a lot.
-
June 10th, 2010, 02:30 PM
#6
Re: Reading image into char array
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|