Solved

How do I read a bitmap or jpeg file into a byte array in Microsoft unmanaged C++?

Posted on 2014-12-14
3
880 Views
Last Modified: 2014-12-24
Hi:

It's been many years since I last did any C++ coding.
I'm writing in VS unmanaged C++.

This is probably a pretty basic question.

How do I read either a bitmap or jpeg file into a byte array?
(Byte is typedef'd as "unsigned char")

Thanks,
JohnB
0
Comment
Question by:jxbma
3 Comments
 
LVL 86

Assisted Solution

by:jkr
jkr earned 250 total points
ID: 40499393
Since you'll end up having to you functions outside the 'std' namespace to obtain e.g. the file's size, why now using the Windows API directly? E.g.

#include <windows.h>
#include <tchar.h>

//...

HANDLE hFile = CreateFile(_T("image.jpg"), FILE_READ,0,NULL, OPEN_EXISTING,0,NULL);

DWORD dwSize = GetFileSize(hFile,NULL);

BYTE* buf = new BYTE[dwSize];

DWORD dwRead = 0;
ReadFile(hFile,(LPVOID)buffer,dwSize,&dwRead,NULL);

CloseHandle(hFile);

Open in new window


(error echecking omitted for brevity)

Using STL classes, that could be like

#include <fstream>
#include <sys/stat.h> // for '_stat()'

using namespace std;

//  ...

ifstram is("image.jpg",ios_base::binary);

struct _stat status;

_stat("image.jpg",&status);

BYTE* buf = new BYTE[status.st_size];

is.read(buf,status.st_size);

Open in new window


Of course, you could still do that the C way, but since using 'fopen()/fread()' was your goal, you'd have asked in the C area (and it is basically similar to the above)
0
 
LVL 32

Accepted Solution

by:
sarabande earned 250 total points
ID: 40501010
the second sample of jkr has a typo and the read statement will not compile because ifstream::read expects a char buffer rather than a byte buffer. normally, you also would call stat function before opening the stream. so when turning jkr's code snippet to a function, it would look like

bool readBinaryFile(const std::string & strFilePath, std::vector<unsigned char>& byteArr)
{
       struct stat filestat = { 0 };
       if (stat(strFilePath.c_str(), &filestat) != 0)
            return false;    // error, probably 'file not found'.  use errno or GetLastError() to know more

       std::ifstream ifs(strFilePath.c_str(), std::ios::binary | std::ios::in);

       if (!ifs)
            return false; // error probably 'access denied'
       // allocate memory
       byteArr.resize(filestat.st_size);

       if (!ifs.read((char*)&byteArr[0], filestat.st_size))
            return false; // the read rarely fails beside you remove the stick while reading
       ifs.close();
       return true;
}

Open in new window


you would call the function like

std::string filename = "c:\\temp\\bitmap.bmp";
std::vector<unsigned char> buffer;

if (readBinaryFile(filename, buffer) && !buffer.empty())
{
        size_t size = buffer.size();
        showBitmap(&buffer[0], size);  // you could pass byte vector as BYTE* to other functions
        ...

Open in new window


Sara
0
 
LVL 1

Author Closing Comment

by:jxbma
ID: 40516914
Thanks man!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now