我的场景:
- 我有一张彩色背景图片 JPG。
- 我在白色背景 JPG 上有一个黑色文本。
- 两张图片大小相同(高度和宽度)
我想在彩色背景图像上覆盖黑色文本和白色背景的图像,即白色背景变得透明以查看其下方的彩色背景。
如何在 C# 中使用 GDI 执行此操作?
谢谢!
我的场景:
我想在彩色背景图像上覆盖黑色文本和白色背景的图像,即白色背景变得透明以查看其下方的彩色背景。
如何在 C# 中使用 GDI 执行此操作?
谢谢!
感谢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");
}
}
}
}
奇迹般有效。谢谢!
如果图像大小相同,则迭代它们并“与”每个像素的颜色。对于白色像素,您应该获得另一张图像的颜色,对于黑色像素,您应该获得黑色。
如果它们的大小不同,请先缩放。
我在脑海中编造这个,但类似:
Color destColor = Color.FromArgb(pixel1.ToArgb() & pixel2.ToArgb());
存在更简单快捷的方法。当您绘制必须部分可见的图像时,您应该使用 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 压缩伪影影响的像素。