gpt4 book ai didi

winforms - C# - 通过特殊方式给图片添加水印

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:23:24 31 4
gpt4 key购买 nike

我需要通过特殊方式给照片加水印。我知道怎么做,但我不知道,怎么做和this中的一样文章。

这是添加水印的方法。我如何更改它以获得带有水印的图像,例如上面的文章?

public static Bitmap AddWatermark(this Bitmap originalImage, Bitmap watermarkImage, WatermarkLocationEnum location)
{
int offsetWidth;
int offsetHeight;
if ((watermarkImage.Width > originalImage.Width) | (watermarkImage.Height > originalImage.Height))
throw new Exception("The watermark must be smaller than the original image.");
Bitmap backgroundImage = new Bitmap((Bitmap)originalImage.Clone());
Bitmap image = new Bitmap(backgroundImage.Width, backgroundImage.Height);
Graphics graphics = Graphics.FromImage(image);
offsetWidth = GetOffsetWidth(image.Width, watermarkImage.Width, location);
offsetHeight = GetOffsetHeight(image.Height, watermarkImage.Height, location);
watermarkImage.SetResolution(backgroundImage.HorizontalResolution, backgroundImage.VerticalResolution);
offsetWidth = Math.Max(offsetWidth - 1, 0);
offsetHeight = Math.Max(offsetHeight - 1, 0);
graphics.DrawImage(watermarkImage, offsetWidth, offsetHeight);
for (int i = offsetWidth; i < (offsetWidth + watermarkImage.Width); i++)
{
for (int j = offsetHeight; j < (offsetHeight + watermarkImage.Height); j++)
{
Color pixel = image.GetPixel(i, j);
if (pixel.A > 0)
{
Color color = Color.FromArgb(pixel.A, pixel.R, pixel.G, pixel.B);
Color imagePixelColor = backgroundImage.GetPixel(i, j);
double alpha = (double)color.A / 255;
Color newColor = Color.FromArgb(255,
(int)((double)imagePixelColor.R * (1.0 - alpha) + alpha * color.R),
(int)((double)imagePixelColor.G * (1.0 - alpha) + alpha * color.G),
(int)((double)imagePixelColor.B * (1.0 - alpha) + alpha * color.B));
backgroundImage.SetPixel(i, j, newColor);
}
}
}
return backgroundImage;
}

//............
Image img = Bitmap.FromFile("DSC00766.JPG");
var wtm = (Bitmap)Bitmap.FromFile("Copyright1.jpg");
((Bitmap)img).AddWatermark(wtm, WatermarkLocationEnum.BottomCenter).Save("new.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

更新

预期结果:

expect result

当前结果:

current result

最佳答案

如果您创建的版权图像是半透明的并且具有像这样的透明背景(使用 Paint.NET):

alt text

您可以从中创建一个 TextureBrush 并使用它在原始图像上绘制版权:

private void button2_Click(object sender, EventArgs e)
{
using (Image image = Image.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"))
using (Image watermarkImage = Image.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\watermark.png"))
using (Graphics imageGraphics = Graphics.FromImage(image))
using (Brush watermarkBrush = new TextureBrush(watermarkImage))
{
imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(0, 0), image.Size));
image.Save(@"C:\Users\Public\Pictures\Sample Pictures\Desert_watermark.jpg");
}
}

产生这个结果:

alt text

关于winforms - C# - 通过特殊方式给图片添加水印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4113900/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com