Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I store the image in matrix form in C#?

I tried a lot using pointer but it is unsafe and not going in correct way?
Posted
Updated 1-Feb-11 22:08pm
v2
Comments
E.F. Nijboer 2-Feb-11 4:06am    
Thanks for updating your question title :-)
Do you mean an image like in graphics? maybe this can help or did yopu try this already?: http://msdn.microsoft.com/en-us/library/5ey6h79d.aspx
shakil0304003 2-Feb-11 4:08am    
Please, share your code.

1 solution

If your image is monochrome you may try something like:
C#
int[,] BitmapToMatrix(Bitmap bmp)
{
    Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
    BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.WriteOnly,
        bmp.PixelFormat);
    int bytesPerPixel = bmpData.Stride / bmp.Width;
    //if you want to access your pixel as matrix[i, j]
    //(i = row index, j = column index)
    //then allocate your matrix like this:
    int[,] matrix = new int[bmp.Height, bmp.Width];
    //we will use pointers
    unsafe
    {
        for (int i = 0; i < bmp.Height; i++)
        {
            byte* p = (byte*)bmpData.Scan0.ToPointer() +
                (i * bmp.Height) * bmpData.Stride;
            for (int j = 0; j < bmp.Width; j++)
            {
                //don't bother with color components,
                //just extract the first pixel value
                byte* pixel = p + j * bytesPerPixel;
                matrix[i, j] = (int)*pixel;
            }
        }
    }
    bmp.UnlockBits(bmpData);
    return matrix;
}


If you don't want to use unsafe code, then you may have a look to:
http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.unlockbits.aspx

If you want to store the colors, then try something like:
C#
Color[,] BitmapToMatrix(Bitmap bmp)
{
    //if you want to access your pixel as matrix[i, j]
    // (i = row index, j = column index)
    //then allocate your matrix like this:
    Color[,] matrix = new Color[bmp.Height, bmp.Width];
    for (int i = 0; i < bmp.Height; i++)
    {
        for (int j = 0; j < bmp.Width; j++)
        {
           //This work for any bitmap format but is very slow
           //if you want to be more efficient,
           //consider using the first solution.
           //But you must then deal with the internal data
           //by yourself to extract the color components
            matrix[i, j] = bmp.GetPixel(j, i);
        }
    }

    return matrix;
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900