2010-03-24 38 views
6

System.Drawing.Bitmap中每個像素的RGB分量設置爲單一純色的最佳方法是什麼?如果可能的話,我想避免手動循環每個像素來做到這一點。GDI +:將所有像素設置爲給定顏色,同時保留現有的alpha值

注意:我想保留原始位圖中相同的alpha分量。我只想改變RGB值。

我看着使用ColorMatrixColorMap,但我找不到任何方式的所有像素設定爲與這兩種方法具體給定的顏色。

回答

13

是的,使用ColorMatrix。它應該是這樣的:

0 0 0 0 0 
    0 0 0 0 0 
    0 0 0 0 0 
    0 0 0 1 0 
    R G B 0 1 

其中R,G和B是更換顏色的縮放的顏色值(由255.0f分)

+0

這不會將每個像素的顏色設置爲特定顏色,是嗎?我敢肯定,這將增加R,G和B每個顏色通道。我希望整個圖像是一個純色,同時保留每個像素的透明度/ alpha。 – Charles 2010-03-24 19:32:48

+1

對角線上的零點會產生黑色,底部的數字會被添加。 – 2010-03-24 19:38:13

+0

啊哈。我沒有想到這一切。我敢打賭,應該完美地工作。我會檢查並馬上回來。 – Charles 2010-03-24 20:55:25

2

最好的(就perf而言,至少)選項是使用Bitmap.LockBits,並循環掃描線中的像素數據,設置RGB值。

由於您不想更改Alpha,因此您將不得不遍歷每個像素 - 沒有單個內存分配可保留Alpha並替換RGB,因爲它們交錯在一起。

+0

+1。謝謝里德,我可能會用它來做我正在做的其他事情。 – Charles 2010-03-24 21:10:46

6

我知道這已經回答了,但基於漢斯順便的回答產生的代碼看起來是這樣的:

public class Recolor 
{ 
    public static Bitmap Tint(string filePath, Color c) 
    { 
     // load from file 
     Image original = Image.FromFile(filePath); 
     original = new Bitmap(original); 

     //get a graphics object from the new image 
     Graphics g = Graphics.FromImage(original); 

     //create the ColorMatrix 
     ColorMatrix colorMatrix = new ColorMatrix(
      new float[][]{ 
        new float[] {0, 0, 0, 0, 0}, 
        new float[] {0, 0, 0, 0, 0}, 
        new float[] {0, 0, 0, 0, 0}, 
        new float[] {0, 0, 0, 1, 0}, 
        new float[] {c.R/255.0f, 
           c.G/255.0f, 
           c.B/255.0f, 
           0, 1} 
       }); 

     //create some image attributes 
     ImageAttributes attributes = new ImageAttributes(); 

     //set the color matrix attribute 
     attributes.SetColorMatrix(colorMatrix); 

     //draw the original image on the new image 
     //using the color matrix 
     g.DrawImage(original, 
      new Rectangle(0, 0, original.Width, original.Height), 
      0, 0, original.Width, original.Height, 
      GraphicsUnit.Pixel, attributes); 

     //dispose the Graphics object 
     g.Dispose(); 

     //return a bitmap 
     return (Bitmap)original; 
    } 
} 

下載一個工作演示在這裏:http://benpowell.org/change-the-color-of-a-transparent-png-image-icon-on-the-fly-using-asp-net-mvc/

相關問題