Solved

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

Posted on 2014-12-14
3
896 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 33

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Load and store *.pnm image file 1 75
PDF library for Delphi 2 103
thread-safe code in c++ 2 83
VS2015 Redefinition errors 4 23
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
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.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

932 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

12 Experts available now in Live!

Get 1:1 Help Now