Travel through pixels in BMP

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

\"enter

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

7条回答
  •  盖世英雄少女心
    2020-11-30 02:52

    You can turn it into an easy-to-access multidimensional array of colors like so:

    using System.Drawing.Imaging;
    using System.Runtime.InteropServices;
    
    // ...
    
    Color[,] GetSection(Image img, Rectangle r) {
        Color[,] r = new Color[r.Width, r.Height]; // Create an array of colors to return
    
        using (Bitmap b = new Bitmap(img)) { // Turn the Image into a Bitmap
            BitmapData bd = b.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); // Lock the bitmap data
            int[] arr = new int[b.Width * b.Height - 1]; // Create an array to hold the bitmap's data
            Marshal.Copy(bd.Scan0, arr, 0, arr.Length); // Copy over the data
            b.UnlockBits(bd); // Unlock the bitmap
    
            for (int i = 0; i < arr.Length; i++) {
                r[i % r.Width, i / r.Width] = Color.FromArgb(arr[i]); // Copy over into a Color structure
            }
        }
    
        return r; // Return the result
    }
    

    You would call it like so:

    Color[,] c = GetSection(myImage, new Rectangle(0, 0, 100, 100)); // Get the upper-left 100x100 pixel block in the image myImage
    for (int x = 0; x < c.GetUpperBound(0); x++) {
        for (int y = 0; y < c.GetUpperBound(1); y++) {
            Color thePixel = c[x, y];
            // do something with the color
        }
    }
    

    And you could traverse the returned array quite quickly in any direction you want at all.

提交回复
热议问题