Scott Carny
Scott Carny

Reputation: 1

Convert a bitmap into 2D byte array in C#?

I've been developing a project with using AForge.NET framework. In my project, I've been trying to get 2D byte array from a grayscale bitmap. There are some solutions posted about this subject on this site and other forums. But I've not get the true result. For instance I used that code:

public static byte[] ImageToByte2(Image img)
{
    byte[] byteArray = new byte[0];
    using (MemoryStream stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        stream.Close();

        byteArray = stream.ToArray();
    }
    return byteArray;
}

After this "MemoryStream" method, I've thought about converting this byte array into 2D. However, when I tested this code sample with 4*8 bitmap, it returns 1100 values into byteArray. Is that normal? Where am I missing?

Upvotes: 0

Views: 5296

Answers (2)

Colonel Software
Colonel Software

Reputation: 1440

please use the following method

public static byte[,] ImageTo2DByteArray(Bitmap bmp)
    {
        int width = bmp.Width;
        int height = bmp.Height;
        BitmapData data = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

        byte[] bytes = new byte[height * data.Stride];
        try
        {
            Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
        }
        finally
        {
            bmp.UnlockBits(data);
        }

        byte[,] result = new byte[height, width];
        for (int y = 0; y < height; ++y)
            for (int x = 0; x < width; ++x)
            {
                int offset = y * data.Stride + x * 3;
                result[y, x] = (byte)((bytes[offset + 0] + bytes[offset + 1] + bytes[offset + 2]) / 3);
            }
        return result;
    }

Upvotes: 1

Matt Kline
Matt Kline

Reputation: 10477

The .NET Image class serves as an interface for two types of images: Bitmap images and Metafile images. The latter consists of a series of instructions to draw something, not an array of pixels like a bitmap. If you take a look at the Bitmap class itself, there's a pair of LockBits methods that will let you extract the pixel data for the images. At the bottom of the linked reference for the Bitmap class, there's even an example of how to do so.

Upvotes: 1

Related Questions