【发布时间】:2010-11-07 11:13:35
【问题描述】:
我的场景:
- 我有一张彩色背景图片 JPG。
- 我有一个白色背景 JPG 上的黑色文本。
- 两张图片大小相同(高度和宽度)
我想用黑色文本和白色背景将图像覆盖在彩色背景图像上,即白色背景变为透明以查看其下方的彩色背景。
如何在 C# 中使用 GDI 做到这一点?
谢谢!
【问题讨论】:
标签: c# transparency gdi jpeg
我的场景:
我想用黑色文本和白色背景将图像覆盖在彩色背景图像上,即白色背景变为透明以查看其下方的彩色背景。
如何在 C# 中使用 GDI 做到这一点?
谢谢!
【问题讨论】:
标签: c# transparency gdi jpeg
如果图像大小相同,则对它们进行迭代并“与”每个像素的颜色。对于白色像素,您应该获得另一张图像的颜色,对于黑色像素,您应该获得黑色。
如果它们的大小不同,请先缩放。
我是在脑海中编造这个,但是像这样:
Color destColor = Color.FromArgb(pixel1.ToArgb() & pixel2.ToArgb());
【讨论】:
感谢GalacticCowboy 我能够想出这个解决方案:
using (Bitmap background = (Bitmap)Bitmap.FromFile(backgroundPath))
{
using (Bitmap foreground = (Bitmap)Bitmap.FromFile(foregroundPath))
{
// check if heights and widths are the same
if (background.Height == foreground.Height & background.Width == foreground.Width)
{
using (Bitmap mergedImage = new Bitmap(background.Width, background.Height))
{
for (int x = 0; x < mergedImage.Width; x++)
{
for (int y = 0; y < mergedImage.Height; y++)
{
Color backgroundPixel = background.GetPixel(x, y);
Color foregroundPixel = foreground.GetPixel(x, y);
Color mergedPixel = Color.FromArgb(backgroundPixel.ToArgb() & foregroundPixel.ToArgb());
mergedImage.SetPixel(x, y, mergedPixel);
}
}
mergedImage.Save("filepath");
}
}
}
}
像魅力一样工作。谢谢!
【讨论】:
存在更简单快捷的方法。绘制必须部分可见的图像时应使用 ImageAttributes。
Image BackImage = Image.FromFile(backgroundPath);
using (Graphics g = Graphics.FromImage(BackImage))
{
using (ForeImage = Image.FromFile(foregroundPath))
{
ImageAttributes imageAttr = new ImageAttributes();
imageAttr.SetColorKey(Color.FromArgb(245, 245, 245), Color.FromArgb(255, 255, 255),
ColorAdjustType.Default);
g.DrawImage(ForeImage, new Rectangle(0, 0, BackImage.Width, BackImage.Height),
0, 0, BackImage.Width, BackImage.Height, GraphicsUnit.Pixel, imageAttr);
}
}
SetColorKey 方法将使指定范围内的颜色透明,因此您可以使白色位图像素透明,包括所有受 jpeg 压缩伪影影响的像素。
【讨论】: