Thursday, June 12, 2008

Convert a Bitmap to a Raw Image in C#

I have a C dll that takes a Bitmap and writes it out to a Raw Image file, but was looking for a solution in C# and found this code on the following site:

/// <summary>
/// Convert a bitmap to a byte array
/// </summary>
/// <param name="bitmap">image to convert</param>
/// <returns>image as bytes</returns>
private byte[] ConvertBitmap(Bitmap bitmap)
    //Code excerpted from Microsoft Robotics Studio v1.5
    BitmapData raw = null;  //used to get attributes of the image
    byte[] rawImage = null; //the image as a byte[]

        //Freeze the image in memory
        raw = bitmap.LockBits(
            new Rectangle(0, 0, (int)bitmap.Width, (int)bitmap.Height),

        int size = raw.Height * raw.Stride;
        rawImage = new byte[size];

        //Copy the image into the byte[]
        System.Runtime.InteropServices.Marshal.Copy(raw.Scan0, rawImage, 0, size);
        if (raw != null)
            //Unfreeze the memory for the image
    return rawImage;

No comments: