2010-08-01 101 views
6

我正在使用位圖C#並想知道如何將顏色PNG圖像轉換爲只有一種顏色。我希望圖像中所有可見的顏色變成白色。透明的部分應保持透明。我將以灰色背景顯示這些。將透明PNG的顏色轉換爲單色

+0

的可能重複[GDI +:將所有像素給出的顏色,同時保留現有的阿爾法值(http://stackoverflow.com/questions/2510013/gdi-set-all- pixel-to-given-color-while-retaining-existing-alpha-value) – 2010-08-01 17:10:55

+0

有什麼我可以添加到我的答案,因爲你還沒有接受任何答案? – Cloudanger 2010-08-13 19:33:29

+0

嗨,對不起,遲交回復。我現在嘗試了代碼,但無法完成工作。我的所有像素都變成白色,並且不會保留png的透明像素。 – jesperlind 2010-08-16 22:07:25

回答

7

其他答案是有益的,讓我去,非常感謝。我不能讓他們工作,但不知道爲什麼。但我也發現,我想保持像素的原始alpha值,使邊緣平滑。這是我想出的。

for (int x = 0; x < bitmap.Width; x++) 
{ 
    for (int y = 0; y < bitmap.Height; y++) 
    { 
     Color bitColor = bitmap.GetPixel(x, y); 
     //Sets all the pixels to white but with the original alpha value 
     bitmap.SetPixel(x, y, Color.FromArgb(bitColor.A, 255, 255, 255)); 
    } 
} 

下面是結果的屏幕轉儲放大幾十倍(頂部原件): alt text http://codeodyssey.se/upload/white-transparent.png

+0

非常感謝! – CareTaker22 2016-10-09 10:39:24

1

嘗試以下代碼:

void Test() 
    { 
     Bitmap bmp = new Bitmap(50, 50);//you will load it from file or resource 

     Color c = Color.Green;//transparent color 

     //loop height and width. 
     // YOU MAY HAVE TO CONVERT IT TO Height X VerticalResolution and 
     // Width X HorizontalResolution 
     for (int i = 0; i < bmp.Height; i++) 
     { 
      for (int j = 0; j < bmp.Width; j++) 
      { 
       var p = bmp.GetPixel(j, i);//get pixle at point 

       //if pixle color not equals transparent 
       if(!c.Equals(Color.FromArgb(p.ToArgb()))) 
       { 
        //set it to white 
        bmp.SetPixel(j,i,Color.White); 
       } 
      } 
     } 
    } 

PS:這不是測試,並以任何方式優化

7

如果圖像不使用透明度alpha通道那麼下面將做:

Bitmap image; 

for (int x = 0; x < image.Width; x++) 
{ 
    for (int y = 0; y < image.Height; y++) 
    { 
     if (image.GetPixel(x, y) != Color.Transparent) 
     { 
      image.SetPixel(x, y, Color.White); 
     } 
    } 
} 
4

SetPixel差不多是最慢的方式來做到這一點。您可以使用ColorMatrix代替:

var newImage = new Bitmap(original.Width, original.Height, 
          original.PixelFormat); 

using (var g = Graphics.FromImage(newImage)) { 
    var matrix = new ColorMatrix(new[] { 
     new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, 
     new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, 
     new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, 
     new float[] { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f }, 
     new float[] { 1.0f, 1.0f, 1.0f, 0.0f, 1.0f } 
    }); 

    var attributes = new ImageAttributes(); 

    attributes.SetColorMatrix(matrix); 

    g.DrawImage(original, 
       new Rectangle(0, 0, original.Width, original.Height), 
       0, 0, original.Width, original.Height, 
       GraphicsUnit.Pixel, attributes); 
} 
+0

當然,它更加優雅,還需要學習全新的色彩空間,色彩操作的新概念,並利用這些新知識來了解您剛剛做了什麼。 :) 我喜歡它! – 2015-02-23 19:02:05

+0

PS:只要「使用System.Drawing;」和「使用System.Drawing.Imaging」,你的C#語法就沒問題。 – 2015-02-23 19:14:40