Getting RGB array from image in C#

前端 未结 5 1112
面向向阳花
面向向阳花 2020-12-10 06:06

I\'m currently writing a C# implementation of a little program which I have written in Java.

I had used BufferedImage.getRGB(int startX, int startY, int w, int

5条回答
  •  我在风中等你
    2020-12-10 06:55

    You'd use Bitmap.LockBits to get direct access to the pixels in a bitmap. Here's a sample implementation, it returns one scanline from the passed bitmap as an int[]:

        int[] getRGB(Bitmap bmp, int line) {
            var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            try {
                var ptr = (IntPtr)((long)data.Scan0 + data.Stride * (bmp.Height - line - 1));
                var ret = new int[bmp.Width];
                System.Runtime.InteropServices.Marshal.Copy(ptr, ret, 0, ret.Length * 4);
                return ret;
            }
            finally {
                bmp.UnlockBits(data);
            }
        }
    

提交回复
热议问题