Convert image into useable byte array in C?

后端 未结 6 975
半阙折子戏
半阙折子戏 2021-01-20 07:04

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!

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 07:29

    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;
        }
    

提交回复
热议问题