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