Travel through pixels in BMP

后端 未结 7 1081
梦谈多话
梦谈多话 2020-11-30 02:32

\"enter

Hi i have a bmp loaded to a BMP object and im requir

7条回答
  •  一生所求
    2020-11-30 03:11

    When you want to doing image processing on huge images GetPixel() method takes long time but I think my algorithm takes less time than other answers , for example you can test this code on 800 * 600 pixels image.


    Bitmap bmp = new Bitmap("SomeImage");
    
    // Lock the bitmap's bits.  
    Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
    BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    
    // Get the address of the first line.
    IntPtr ptr = bmpData.Scan0;
    
    // Declare an array to hold the bytes of the bitmap.
    int bytes = bmpData.Stride * bmp.Height;
    byte[] rgbValues = new byte[bytes];
    byte[] r = new byte[bytes / 3];
    byte[] g = new byte[bytes / 3];
    byte[] b = new byte[bytes / 3];
    
    // Copy the RGB values into the array.
    Marshal.Copy(ptr, rgbValues, 0, bytes);
    
    int count = 0;
    int stride = bmpData.Stride;
    
    for (int column = 0; column < bmpData.Height; column++)
    {
        for (int row = 0; row < bmpData.Width; row++)
        {
            b[count] = (byte)(rgbValues[(column * stride) + (row * 3)]);
            g[count] = (byte)(rgbValues[(column * stride) + (row * 3) + 1]);
            r[count++] = (byte)(rgbValues[(column * stride) + (row * 3) + 2]);
        }
    }
    

提交回复
热议问题