【发布时间】:2014-12-11 15:20:34
【问题描述】:
我需要为更大的图像添加透明水印。到目前为止,通过所有的谷歌搜索,我来到了你身边 该代码似乎可以工作,但水图像没有正确放置,并且似乎扭曲并失去透明度。请让我知道如何解决此问题。如果有更好的方法来实现这一点,请告诉我。
主图像 640x480
水印图片 100x86
public static class ImageHelper
{
#region Public Methods and Operators
public static Bitmap BitmapSourceToBitmap(BitmapSource bitmapsource)
{
Bitmap bitmap;
using (var outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapsource));
enc.Save(outStream);
bitmap = new Bitmap(outStream);
}
return bitmap;
}
public static BitmapSource BitmapToBitmapSource(Bitmap source)
{
return Imaging.CreateBitmapSourceFromHBitmap(
source.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
#endregion
#region Methods
public static Image BitmapSourceToImage(BitmapSource image)
{
var ms = new MemoryStream();
var encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(ms);
ms.Flush();
return Image.FromStream(ms);
}
public static Bitmap Superimpose(Bitmap largeBmp, Bitmap smallBmp)
{
Graphics g = Graphics.FromImage(largeBmp);
g.CompositingMode = CompositingMode.SourceOver;
// smallBmp.MakeTransparent();
int margin = 5;
int x = largeBmp.Width - smallBmp.Width - margin;
int y = largeBmp.Height - smallBmp.Height - margin;
g.DrawImage(smallBmp, new Point(x, y));
return largeBmp;
}
#endregion
}
调用代码。
var fs = new FileStream(path, FileMode.Create);
BitmapSource bitmap = new BitmapImage(new Uri(ImagePath, UriKind.Absolute));
BitmapSource Logobitmap = new BitmapImage(new Uri(logoPath, UriKind.Absolute));
bitmap =
ImageHelper.BitmapToBitmapSource(
ImageHelper.Superimpose(
ImageHelper.BitmapSourceToBitmap(bitmap),
ImageHelper.BitmapSourceToBitmap(Logobitmap)));
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(fs);
fs.Close();
【问题讨论】:
-
确保两个位图具有相同的 dpi 设置;最好设置它!
-
使用半透明位图在不透明位图上绘画将产生不透明位图,根据每个像素的透明度级别混合颜色。如果要获得半透明水印,则需要使用 setpixel 更改像素。对于这么小的水印图像来说不是什么大问题,除非您需要快速更改大量图像。那么你会想要使用lockbits..