10

Bitmapには方法がありますが、MakeTransparentある色を別の色に変えるのに似たような方法はありますか?

// This sets Color.White to transparent
Bitmap myBitmap = new Bitmap(sr.Stream);
myBitmap.MakeTransparent(System.Drawing.Color.White);

このようなことができるものはありますか?

Bitmap myBitmap = new Bitmap(sr.Stream);
myBitmap.ChangeColor(System.Drawing.Color.Black, System.Drawing.Color.Gray);
4

4 に答える 4

4

この回答からコードを持ち上げる:

public static class BitmapExtensions
{
    public static Bitmap ChangeColor(this Bitmap image, Color fromColor, Color toColor)
    {
        ImageAttributes attributes = new ImageAttributes();
        attributes.SetRemapTable(new ColorMap[]
        {
            new ColorMap()
            {
                OldColor = fromColor,
                NewColor = toColor,
            }
        }, ColorAdjustType.Bitmap);

        using (Graphics g = Graphics.FromImage(image))
        {
            g.DrawImage(
                image,
                new Rectangle(Point.Empty, image.Size),
                0, 0, image.Width, image.Height,
                GraphicsUnit.Pixel,
                attributes);
        }

        return image;
    }
}

ベンチマークはしていませんが、これは GetPixel/SetPixel をループで実行しているどのソリューションよりも高速です。また、もう少し簡単です。

于 2019-02-01T21:51:16.247 に答える
-1

そのためにSetPixelを使用できます。

private void ChangeColor(Bitmap s, System.Drawing.Color source, System.Drawing.Color target)
{
    for (int x = 0; x < s.Width; x++)
    {
        for (int y = 0; y < s.Height; y++)
        {
            if (s.GetPixel(x, y) == source)
                s.SetPixel(x, y, target);
        }                
    }
}

GetPixel と SetPixel は、gdiplus.dll 関数 GdipBitmapGetPixel と GdipBitmapSetPixel のラッパーです。

備考:

ビットマップの形式によっては、GdipBitmapGetPixel は GdipBitmapSetPixel によって設定された値と同じ値を返さない場合があります。たとえば、ピクセル形式が 32bppPARGB の Bitmap オブジェクトで GdipBitmapSetPixel を呼び出すと、ピクセルの RGB コンポーネントが事前に乗算されます。その後 GdipBitmapGetPixel を呼び出すと、丸めのために異なる値が返される場合があります。また、色深度が 16 ビット/ピクセルの Bitmap オブジェクトで GdipBitmapSetPixel を呼び出すと、32 ビットから 16 ビットへの変換中に情報が失われ、その後の GdipBitmapGetPixel の呼び出しで別の値が返される可能性があります。

于 2013-05-02T19:33:43.350 に答える
-2

ピクセルを操作せずに画像の色空間を変更する方法を提供するライブラリが必要です。LeadTools には、色の交換など、色空間の変更をサポートする、使用できる非常に広範な画像ライブラリがあります。

于 2013-05-02T19:40:54.113 に答える