簡體   English   中英

如何使用 BitmapData 進行 Bitmap 處理?

[英]How to do Bitmap processing using BitmapData?

我構建了一個小型測試示例,目標是將.png中的所有像素更改為白色。 我正在使用BitmapData進行操作,因為據我了解,性能更好。 如果我能讓它工作; 然后我可以更改要更改的像素並添加不同的條件來更改像素顏色。 但我堅持這個簡單的測試。

這是我的 C#:

public static void TestConvertAllBlackBitmapToAllWhite()
{
    string allBlackPNGFullFilePath = @"C:\Users\{Username}\Desktop\50x50AllBlack.png";
    Bitmap allBlackBitmap = new Bitmap(allBlackPNGFullFilePath);

    Bitmap newBitmap = (Bitmap)allBlackBitmap.Clone();

    Size size = newBitmap.Size;
    PixelFormat pixelFormat = newBitmap.PixelFormat;
    byte bitDepth = (byte)(pixelFormat == PixelFormat.Format32bppArgb ? 4 : 3);
    Rectangle rectangle = new Rectangle(Point.Empty, size);
    BitmapData bitmapData = newBitmap.LockBits(rectangle, ImageLockMode.ReadOnly, pixelFormat);
    int dataSize = bitmapData.Stride * bitmapData.Height;
    byte[] data = new byte[dataSize];
    Marshal.Copy(bitmapData.Scan0, data, 0, dataSize);

    Color white = Color.White;

    for (int y = 0; y < size.Height; y++)
    {
        for (int x = 0; x < size.Width; x++)
        {
            // Get Index
            int index = y * bitmapData.Stride + x * bitDepth;

            // Set Pixel Color
            data[index] = white.B;
            data[index + 1] = white.G;
            data[index + 2] = white.R;
        }
    }

    Marshal.Copy(data, 0, bitmapData.Scan0, data.Length);
    newBitmap.UnlockBits(bitmapData);

    // Save New Converted Bitmap
    string originalFileName = Path.GetFileNameWithoutExtension(allBlackPNGFullFilePath);
    string directory = Path.GetDirectoryName(allBlackPNGFullFilePath);
    string newBitmapFileName = originalFileName + "_Converted";
    string newBitmapFullFileName = directory + Path.DirectorySeparatorChar.ToString() + newBitmapFileName + ".png";

    newBitmap.Save(newBitmapFullFileName, ImageFormat.Png);
}

我的輸入是全黑的 50x50 .png 全黑 50 x 50 PNG

問題是我得到的 output 是另一個全黑.png而不是全白的。

如何修復我的簡單示例代碼以生成全白的.png

任何幫助/指導將不勝感激。

正如@Taw 指出的那樣

這條線上有一點:

BitmapData bitmapData = newBitmap.LockBits(rectangle, ImageLockMode.ReadOnly, pixelFormat);

ImageLockMode設置為ReadOnly 因為我在循環時對BitmapData進行了更改; ImageLockMode應該是ReadWrite

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM