improving speed of GetPixel function in c#

Deadly 提交于 2019-12-12 02:43:41

问题


i need to read getpixel of bmp with speed but is very low i used of LockBits

     private void LockUnlockBitsExample(Bitmap bmp)
    {

        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
        System.Drawing.Imaging.BitmapData bmpData =
            bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
            bmp.PixelFormat);
        IntPtr ptr = bmpData.Scan0;

        int bytes  = Math.Abs(bmpData.Stride) * bmp.Height;
        rgbValues = new byte[bytes];

        System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
        bmp.UnlockBits(bmpData);
    }

and this function

        private Color GetMyPixel(byte[] rgbValues,Bitmap bmp, int x,int y )
    {

        int index= (bmp.Width*y+x)*3;
        Color MyColor = Color.FromArgb(rgbValues[index], rgbValues[index + 1], rgbValues[index + 2]);
        return MyColor;
    }

but output of my function is different from original getpixel


回答1:


I have code in VB for some reason that does almost the exact same thing as you, so I hope this helps. You can try the following modification to GetMyPixel:

Use Stride instead of Width and invert the byte order in your call to FromArgb.

private Color GetMyPixel(byte[] rgbValues,Bitmap bmp, int x,int y )
{
   int index= (bmp.Stride*y+x*3);        
   if (index > rgbValues.Length - 3)
   index = rgbValues.Length - 3;
   Color MyColor = Color.FromArgb(rgbValues[index+2], rgbValues[index + 1], rgbValues[index]);         
    return MyColor;
} 



回答2:


In this line:

int index= (bmp.Width*y+x)*3;

I believe that bmp.Stride must be used instead of bmp.Width. Also check assumption that PixelFormat is 24 bits per pixel.

Another thing are color indexes: blue is first (index), then green (index+1), then red (index + 2).




回答3:


You should check this post out :working with lockbits

it helped me a lot when i did something similar



来源:https://stackoverflow.com/questions/12510714/improving-speed-of-getpixel-function-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!