WPF实现图片合成或加水印的方法【2种方法】

2019-12-30 16:53:27于海丽

第二种方式

利用原来的GDI+方式


private BitmapSource MakePictureGDI(string bgImagePath, string headerImagePath, string signature)
{
  GDI.Image bgImage = GDI.Bitmap.FromFile(bgImagePath);
  GDI.Image headerImage = GDI.Bitmap.FromFile(headerImagePath);
  //新建一个画板,画板的大小和底图一致
  System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(bgImage.Width, bgImage.Height);
  System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
  //设置高质量插值法
  g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
  //设置高质量,低速度呈现平滑程度
  g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  //清空画布并以透明背景色填充
  g.Clear(System.Drawing.Color.Transparent);
  //先在画板上面画底图
  g.DrawImage(bgImage, new GDI.Rectangle(0, 0, bitmap.Width, bitmap.Height));
  //再在画板上画头像
  int x = (bgImage.Width / 2 - headerImage.Width) / 2;
  int y = (bgImage.Height - headerImage.Height) / 2 - 100;
  g.DrawImage(headerImage, new GDI.Rectangle(x, y, headerImage.Width, headerImage.Height),
               new GDI.Rectangle(0, 0, headerImage.Width, headerImage.Height),
               GDI.GraphicsUnit.Pixel);
  //在画板上写文字
  using (GDI.Font f = new GDI.Font("Arial", 20, GDI.FontStyle.Bold))
  {
    using (GDI.Brush b = new GDI.SolidBrush(GDI.Color.White))
    {
      float fontWidth = g.MeasureString(signature, f).Width;
      float x2 = (bgImage.Width / 2 - fontWidth) / 2;
      float y2 = y + headerImage.Height + 20;
      g.DrawString(signature, f, b, x2, y2);
    }
  }
  try
  {
    string savePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"GDI+合成.jpg";
    bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
    return ToBitmapSource(bitmap);
  }
  catch (System.Exception e)
  {
    throw e;
  }
  finally
  {
    bgImage.Dispose();
    headerImage.Dispose();
    g.Dispose();
  }
}
#region GDI+ Image 转化成 BitmapSource
[System.Runtime.InteropServices.DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);
public BitmapSource ToBitmapSource(GDI.Bitmap bitmap)
{
  IntPtr ip = bitmap.GetHbitmap();
  BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
    ip, IntPtr.Zero, System.Windows.Int32Rect.Empty,
    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
  DeleteObject(ip);//释放对象
  return bitmapSource;
}
#endregion

附:完整实例代码点击此处本站下载。

希望本文所述对大家C#程序设计有所帮助。


注:相关教程知识阅读请移步到c#教程频道。