2
我試圖讓圖像顯示其中一種顏色替換爲白色阿爾法,以便我可以將圖層疊加在其他圖像上。我已經知道了,所以我可以很容易地改變顏色,但改變它是透明的,正在逃避我。這是我的代碼,使用C#和WPF。在圖像處理中使用Alpha
private void SetAlpha(string location)
{
//bmp is a bitmap source that I load from an image
bmp = new BitmapImage(new Uri(location));
int[] pixels = new int[(int)bmp.Width * (int)bmp.Height];
//still not sure what 'stride' is. Got this part from a tutorial
int stride = (bmp.PixelWidth * bmp.Format.BitsPerPixel + 7)/8;
bmp.CopyPixels(pixels, stride, 0);
int oldColor = pixels[0];
int red = 255;
int green = 255;
int blue = 255;
int alpha = 0;
int color = (alpha << 24) + (red << 16) + (green << 8) + blue;
for (int i = 0; i < (int)bmp.Width * (int)bmp.Height; i++)
{
if (pixels[i] == oldColor)
{
pixels[i] = color;
}
}
//remake the bitmap source with these pixels
bmp = BitmapSource.Create(bmp.PixelWidth, bmp.PixelHeight, bmp.DpiX, bmp.DpiY, bmp.Format, bmp.Palette, pixels, stride);
}
}
我有兩個圖像,我正在測試這個。 Image1就像我將要處理的那樣,原始圖像沒有透明度。 Image2已經具有透明度。我認爲只需從image2(0x00ffffff)中獲取值很容易,但這隻會使其變爲白色並遮蓋任何背後的圖像。
兩張圖片都是png,兩者的格式都是Bgr32。
有誰知道如何讓圖像變得透明嗎?
謝謝! 更改 bmp = BitmapSource.Create(bmp.PixelWidth,bmp.PixelHeight,bmp.DpiX,bmp.DpiY,bmp.Format,bmp.Palette,pixels,stride); 到 bmp = BitmapSource.Create(bmp.PixelWidth,bmp.PixelHeight,bmp.DpiX,bmp.DpiY,bmp.Format,bmp.Palette,pixels,stride); 固定它。 有什麼我正在做的顏色讓你緊張? – Califer 2009-09-01 02:49:38
不......這幾乎可以。我只是想確保你明白你在做什麼,而不僅僅是從教程中獲取東西:) – 2009-09-01 07:16:17
糟糕,我沒有實際發佈修復:P第二個bmp.Format應該是'System.Windows.Media。而不是PixelFormats.Bgra32'。 – Califer 2009-09-01 13:26:05