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: http://www.developerfusion.co.uk/forums/p/27321/160103/#160103

/// <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[]

    try
    {
        //Freeze the image in memory
        raw = bitmap.LockBits(
            new Rectangle(0, 0, (int)bitmap.Width, (int)bitmap.Height),
            ImageLockMode.ReadOnly,
            PixelFormat.Format24bppRgb
        );

        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);
    }
    finally
    {
        if (raw != null)
        {
            //Unfreeze the memory for the image
            bitmap.UnlockBits(raw);
        }
    }
    return rawImage;
}



No comments: