Read byte from JPEG file??

Jun 22, 2010 at 9:44pm
Please advise me how to read the JPEG file into byte array. I was trying to use ifstream and ios::binary as following:

#include <fstream>
#include <iostream>

using namespace std;

int main()
{
ifstream myFile;
myFile.open("butterfly.jpeg", ios::in | ios::binary);

//not the end of file
while(!myFile.eof())
{
int line;
myFile >> line;
cout << line << endl;
}
}

Though, what I got was infinitive print of "4" like this:
4
4
4
4
...

Thank you.
Jun 22, 2010 at 9:57pm
What are you expecting outputting JPEG data to the console to achieve?
Jun 22, 2010 at 10:17pm
materithe wrote:
Please advise me how to read the JPEG file into byte array


You could use something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <fstream>
#include <sstream>

int main()
{
    std::ifstream ifs("butterfly.jpeg", ios::in | ios::binary); // input file
    std::ostringstream oss; // output to string

    int len;
    char buf[1024];
    while((len = ifs.readsome(buf, 1024)) > 0)
    {
        oss.write(buf, len);
    }

    std::string data = oss.str(); // get string data out of stream
}
Jun 23, 2010 at 1:33am
Thanks,

I will try this right now. What I have to do is to write a JPEG decoder (taking in a JPEG file and produce a BMP file).

So right now, I try to get the file into stream of bytes and apply reverse compression algorithms.

Thank you. If you have any more advise for me, please let me know.
Jun 23, 2010 at 1:56am
Dear Galik,

I get compiling error with your code for line 7 as it says:

Multiple markers at this line
- unused variable 'in'
- unused variable 'binary'
- `ios' has not been declared
- `in' was not declared in this
scope
- `binary' was not declared in
this scope

I am using Eclipse IDE with MinGW compiler.

Thank you.
Jun 23, 2010 at 6:28am
This should work:
std::ifstream ifs("butterfly.jpeg", std::ios::in | std::ios::binary);

Why don't you use a jpeg library for this?

http://www.ijg.org/
Topic archived. No new replies allowed.