Get all pixel information of an image efficiently

后端 未结 2 679
囚心锁ツ
囚心锁ツ 2020-12-03 20:15

I made a program to get all image pixel RGB color codes from picture. Basically, it sets y position on constant and changes x position zero to width and also y by looping. <

相关标签:
2条回答
  • 2020-12-03 20:28

    Getting pixel information shouldn't take that long. Can you log the time it takes myimage() to run? The slowness might be somewhere else. Also try removing the line that begins with textBox2.AppendText in myimage() and see how fast it runs then.

    0 讨论(0)
  • 2020-12-03 20:33

    Take a look at this:

    var data = mypic.LockBits(
        new Rectangle(Point.Empty, mypic.Size),
        ImageLockMode.ReadWrite, mypic.PixelFormat);
    var pixelSize = data.PixelFormat == PixelFormat.Format32bppArgb ? 4 : 3; // only works with 32 or 24 pixel-size bitmap!
    var padding = data.Stride - (data.Width * pixelSize);
    var bytes = new byte[data.Height * data.Stride];
    
    // copy the bytes from bitmap to array
    Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
    
    var index = 0;
    var builder = new StringBuilder();
    
    for (var y = 0; y < data.Height; y++)
    {
        for (var x = 0; x < data.Width; x++)
        {
            Color pixelColor = Color.FromArgb(
                pixelSize == 3 ? 255 : bytes[index + 3], // A component if present
                bytes[index + 2], // R component
                bytes[index + 1], // G component
                bytes[index]      // B component
                );
    
            builder
                .Append("  ")
                .Append(pixelColor.R)
                .Append("     ")
                .Append(pixelColor.G)
                .Append("     ")
                .Append(pixelColor.B)
                .Append("     ")
                .Append(pixelColor.A)
                .AppendLine();
    
            index += pixelSize;
        }
    
        index += padding;
    }
    
    // copy back the bytes from array to the bitmap
    Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);
    
    textBox2.Text = builder.ToString();
    

    Is just an example, read some good tutorials about LockBits and imaging in general to understand clearly what happens.

    0 讨论(0)
提交回复
热议问题