djs22
djs22

Reputation: 1156

Convert image into useable byte array in C?

Does anyone know how to open an image, specifically a jpg, to a byte array in C or C++? Any form of help is appreciated.

Thanks!

Upvotes: 3

Views: 12354

Answers (6)

rmp
rmp

Reputation: 1083

Here is how I would do it using GDIPlus Bitmap.LockBits method defined in the header GdiPlusBitmap.h:

    Gdiplus::BitmapData bitmapData;
    Gdiplus::Rect rect(0, 0, bitmap.GetWidth(), bitmap.GetHeight());

    //get the bitmap data
    if(Gdiplus::Ok == bitmap.LockBits(
                        &rect, //A rectangle structure that specifies the portion of the Bitmap to lock.
                        Gdiplus::ImageLockModeRead | Gdiplus::ImageLockModeWrite, //ImageLockMode values that specifies the access level (read/write) for the Bitmap.            
                        bitmap.GetPixelFormat(),// PixelFormat values that specifies the data format of the Bitmap.
                        &bitmapData //BitmapData that will contain the information about the lock operation.
                        ))
    {
         //get the lenght of the bitmap data in bytes
         int len = bitmapData.Height * std::abs(bitmapData.Stride);

         BYTE* buffer = new BYTE[len];
         memcpy(bitmapData.Scan0, buffer, len);//copy it to an array of BYTEs

         //... 

         //cleanup
         pBitmapImageRot.UnlockBits(&bitmapData);       
         delete []buffer;
    }

Upvotes: 1

bear24rw
bear24rw

Reputation: 4617

OpenCV can also do this.

http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/index.html

search for: "Accessing image elements"

Upvotes: 0

Norman Ramsey
Norman Ramsey

Reputation: 202465

I have my students use netpbm to represent images because it comes with a handy C library, but you can also put images into text form, create them by hand, and so on. The nice thing here is that you can convert all sorts of images, not just JPEGs, into PBM format, using command-line tools the Unix way. The djpeg tool is available a number of places including the JPEG Club. Students with relatively little experience can write some fairly sophisticated programs using this format.

Upvotes: 0

Malvineous
Malvineous

Reputation: 27300

The ImageMagick library can do this too, although often it provides enough image manipulation functions that you can do many things without needing to convert the image to a byte array and handle it yourself.

Upvotes: 2

Thomas Matthews
Thomas Matthews

Reputation: 57678

Check out the source code for wxImage in the wxWidgets GUI Framework. You will most likely be interested in the *nix distribution.

Another alternative is the GNU Jpeg library.

Upvotes: 1

cpalmer
cpalmer

Reputation: 1117

You could try the DevIL Image Library I've only used it in relation to OpenGL related things, but it also functions as just a plain image loading library.

Upvotes: 1

Related Questions