c# - 使用 Lockbits 替换图像的颜色

标签 c# .net vb.net image-processing bitmap

首先,我会指出我将接受 C# 或 VB.NET 解决方案。

我正在尝试重构这段旧代码,以避免使用 GetPixel/SetPixel 方法的坏习惯和性能低下:

<Extension>
Public Function ChangeColor(ByVal sender As Image, 
                            ByVal oldColor As Color, 
                            ByVal newColor As Color) As Image

    Dim bmp As New Bitmap(sender.Width, sender.Height, sender.PixelFormat)

    Dim x As Integer = 0
    Dim y As Integer = 0

    While (x < bmp.Width)

        y = 0
        While y < bmp.Height
            If DirectCast(sender, Bitmap).GetPixel(x, y) = oldColor Then
                bmp.SetPixel(x, y, newColor)
            End If
            Math.Max(Threading.Interlocked.Increment(y), y - 1)
        End While
        Math.Max(Threading.Interlocked.Increment(x), x - 1)

    End While

    Return bmp

End Function

所以,在阅读了投票最多的解决方案后 here 使用 LockBits 方法,我试图使代码适应我的需要,使用 Color 作为参数而不是字节序列(因为本质上它们是相同的):

<Extension>
Public Function ChangeColor(ByVal sender As Image, 
                            ByVal oldColor As Color, 
                            ByVal newColor As Color) As Image

   Dim bmp As Bitmap = DirectCast(sender.Clone, Bitmap)

   ' Lock the bitmap's bits.
   Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height)
   Dim bmpData As BitmapData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat)

    ' Get the address of the first line.
    Dim ptr As IntPtr = bmpData.Scan0

    ' Declare an array to hold the bytes of the bitmap. 
    Dim numBytes As Integer = (bmpData.Stride * bmp.Height)
    Dim rgbValues As Byte() = New Byte(numBytes - 1) {}

    ' Copy the RGB values into the array.
    Marshal.Copy(ptr, rgbValues, 0, numBytes)

    ' Manipulate the bitmap.
    For i As Integer = 0 To rgbValues.Length - 1 Step 3

      If (Color.FromArgb(rgbValues(i), rgbValues(i + 1), rgbValues(i + 2)) = oldColor) Then
          rgbValues(i) = newColor.R
          rgbValues(i + 1) = newColor.G
          rgbValues(i + 2) = newColor.B
      End If

    Next i

    ' Copy the RGB values back to the bitmap.
    Marshal.Copy(rgbValues, 0, ptr, numBytes)

    ' Unlock the bits.
    bmp.UnlockBits(bmpData)

    Return bmp

End Function

我对扩展方法有两个问题:第一个是,如果像素格式不是原始示例中的 Format24bppRgb ,那么一切都会出错:循环中抛出“IndexOutOfRange”异常。我想这是因为我正在读取 3 个字节 (RGB) 而不是 4 个字节 (ARGB),但我不确定如何使其适应我可以传递给函数的任何源像素格式。

第二个是,如果我按照原始 C# 示例使用 Format24bppRgb,颜色将变为黑色。

请注意,我不确定我链接到的 C# 问题中给出的原始解决方案是否错误,因为根据他们的评论,它似乎在某种程度上是错误的。

这就是我尝试使用它的方式:

    ' This function creates a bitmap of a solid color.
    Dim srcImg As Bitmap = ImageUtil.CreateSolidcolorBitmap(New Size(256, 256), Color.Red)
    Dim modImg As Image = srcImg.ChangeColor(Color.Red, Color.Blue)

    PictureBox1.BackgroundImage = srcImg 
    PictureBox2.BackgroundImage = modImg 

最佳答案

I suppose this is because I'm reading 3 bytes (RGB) instead of 4 (ARGB)

是的,这就是重点。如果要操作原始图像内容,则必须依赖PixelFormat。并且您必须区分索引格式(8bpp 或更少),其中 BitmapData 中的像素不是颜色,而是调色板的索引。

public void ChangeColor(Bitmap bitmap, Color from, Color to)
{
    if (Image.GetPixelFormatSize(bitmap.PixelFormat) > 8)
    {
        ChangeColorHiColoredBitmap(bitmap, from, to);
        return;
    }

    int indexFrom = Array.IndexOf(bitmap.Palette.Entries, from);
    if (indexFrom < 0)
        return; // nothing to change

    // we could replace the color in the palette but we want to see an example for manipulating the pixels
    int indexTo = Array.IndexOf(bitmap.Palette.Entries, to);
    if (indexTo < 0)
        return; // destination color not found - you can search for the nearest color if you want

    ChangeColorIndexedBitmap(bitmap, indexFrom, indexTo);
}

private unsafe void ChangeColorHiColoredBitmap(Bitmap bitmap, Color from, Color to)
{
    int rawFrom = from.ToArgb();
    int rawTo = to.ToArgb();

    BitmapData data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), ImageLockMode.ReadWrite, bitmap.PixelFormat);
    byte* line = (byte*)data.Scan0;
    for (int y = 0; y < data.Height; y++)
    {
        for (int x = 0; x < data.Width; x++)
        {
            switch (data.PixelFormat)
            {
                case PixelFormat.Format24bppRgb:
                    byte* pos = line + x * 3;
                    int c24 = Color.FromArgb(pos[0], pos[1], pos[2]).ToArgb();
                    if (c24 == rawFrom)
                    {
                        pos[0] = (byte)(rawTo & 0xFF);
                        pos[1] = (byte)((rawTo >> 8) & 0xFF);
                        pos[2] = (byte)((rawTo >> 16) & 0xFF);
                    }
                    break;
                case PixelFormat.Format32bppRgb:
                case PixelFormat.Format32bppArgb:
                    int c32 = *((int*)line + x);
                    if (c32 == rawFrom)
                        *((int*)line + x) = rawTo;
                    break;
                default:
                    throw new NotSupportedException(); // of course, you can do the same for other pixelformats, too
            }
        }

        line += data.Stride;
    }

    bitmap.UnlockBits(data);
}

private unsafe void ChangeColorIndexedBitmap(Bitmap bitmap, int from, int to)
{
    int bpp = Image.GetPixelFormatSize(bitmap.PixelFormat);
    if (from < 0 || to < 0 || from >= (1 << bpp) || to >= (1 << bpp))
        throw new ArgumentOutOfRangeException();

    if (from == to)
        return;

    BitmapData data = bitmap.LockBits(
        new Rectangle(Point.Empty, bitmap.Size),
        ImageLockMode.ReadWrite,
        bitmap.PixelFormat);

    byte* line = (byte*)data.Scan0;

    // scanning through the lines
    for (int y = 0; y < data.Height; y++)
    {
        // scanning through the pixels within the line
        for (int x = 0; x < data.Width; x++)
        {
            switch (bpp)
            {
                case 8:
                    if (line[x] == from)
                        line[x] = (byte)to;
                    break;
                case 4:
                    // First pixel is the high nibble. From and To indices are 0..16
                    byte nibbles = line[x / 2];
                    if ((x & 1) == 0 ? nibbles >> 4 == from : (nibbles & 0x0F) == from)
                    {
                        if ((x & 1) == 0)
                        {
                            nibbles &= 0x0F;
                            nibbles |= (byte)(to << 4);
                        }
                        else
                        {
                            nibbles &= 0xF0;
                            nibbles |= (byte)to;
                        }

                        line[x / 2] = nibbles;
                    }
                    break;
                case 1:
                    // First pixel is MSB. From and To are 0 or 1.
                    int pos = x / 8;
                    byte mask = (byte)(128 >> (x & 7));
                    if (to == 0)
                        line[pos] &= (byte)~mask;
                    else
                        line[pos] |= mask;
                    break;
            }
        }

        line += data.Stride;
    }

    bitmap.UnlockBits(data);
}

关于c# - 使用 Lockbits 替换图像的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33562053/

相关文章:

c# - 两条线段在 c# 或 vb.net 中使用 xna 相交吗?

c# - system.invalidoperationexception : collection was modified; enumeration operation may not execute. 需要想法吗?

c# - MultipleActiveResultSets=True 或多个连接?

c# - 导致 Socket.Receive 返回的最小字节数是多少?

c# - 为什么此参数不符合 CLS?

html - asp.net 如何使用超链接将数据从一页显示到另一页

c# - 如何在动态生成的C#代码中初始化各种类型变量?

c# - 领域驱动设计中对持久性的调用在哪里

c# - 在 C# 中使用来自服务器资源管理器的数据连接

c# - 处理线程中 catch block 内抛出的异常的最佳实践。 (。网)