在图像处理中使用 Alpha
我正在尝试获取要显示的图像,其中一种颜色替换为白色 Alpha,以便我可以将其分层在其他图像之上。我已经有了它,这样我就可以很容易地改变颜色,但是将其更改为透明却让我无法实现。这是我的代码,使用 C# 和 WPF。
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。
有谁知道如何使图像透明吗?
I'm trying to get an image to display with one of the colors replaced with a white alpha so that I can layer it on top of other images. I've got it so that I can change colors easily enough, but changing it to be transparent is eluding me. Here's my code, using C# and WPF.
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);
}
}
I've got two images that I'm testing this with. Image1 is like what I am going to be working on, no transparency in the original image. Image2 already has transparency. I thought it would be easy to just grab the value from image2 (0x00ffffff) but that just makes it white and covers up any images behind.
Both images are png, and the format for both is Bgr32.
Does anyone know how to get the image to be transparent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 Bgra32 怎么样?
还要确保您了解颜色在内存中的表示方式以及 alpha 的含义。
How about using Bgra32?
Also make sure you understand how the color is represented in memory and what alpha means.