0

我正在使用以下代码来调整图像大小。现在,我需要使用Magick.NET在此图像上应用水印。

        var response = client.GetObject(request).ResponseStream;
        MagickImage image = new MagickImage(response);
        MagickGeometry size = new MagickGeometry(imgWidth, imgHeight);
        size.IgnoreAspectRatio = maintainAspectRatio;                                                       
        image.Resize(size);   


        Bitmap watermarkObj = (Bitmap)Bitmap.FromFile("G:/Images/watermark.png");
        Graphics imageGraphics = Graphics.FromImage(image.ToBitmap());
        Point point = new Point(image.Width - 118, image.Height - 29);                            
        imageGraphics.DrawImage(watermarkObj, point); 
        image.write("G:/Images/ProcessedImage.JPG");

工作代码:

            MagickGeometry size = new MagickGeometry(imgWidth, imgHeight);
            size.IgnoreAspectRatio = maintainAspectRatio;                                                       
            image.Resize(size);   


            Bitmap watermarkObj = (Bitmap)Bitmap.FromFile("G:/Images/watermark.png");
            Bitmap objImg = new Bitmap("G:/Images/OriginalImage.jpg");
            Graphics imageGraphics = Graphics.FromImage(objImg);
            Point point = new Point(image.Width - 118, image.Height - 29);                            
            imageGraphics.DrawImage(watermarkObj, point); 
            objImg.save("G:/Images/ProcessedImage.JPG");

那么,谁能帮助我如何使用 imagemagick 来做到这一点?原因是当我在图形中传递 imageObject 时,它不会应用水印,而当我传递 .net 图像对象时,它会应用水印。

4

1 回答 1

3

您的代码不起作用,因为image.ToBitmap()创建了一个新的位图。当您调用时,image.write("G:/Images/ProcessedImage.JPG");您正在保存image实例的未修改版本。您应该改为执行以下操作。

using (MagickImage image = new MagickImage(response))
{
  MagickGeometry size = new MagickGeometry(imgWidth, imgHeight);
  size.IgnoreAspectRatiomaintainAspectRatio;                                   
  image.Resize(size);

  using (Bitmap watermarkObj = Bitmap)Bitmap.FromFile("G:/Images/watermark.png"))
  {
    using (Bitmap imageObj = image.ToBitmap())
    {
      using (Graphics imageGraphics = Graphics.FromImage(imageObj))
      {
        Point point = new Point(image.Width - 118, image.Height - 29);
        imageGraphics.DrawImage(watermarkObj, point);
        imageObj.Save("G:/Images/ProcessedImage.JPG");
      }
    }
  }
}

另请注意,我添加了using语句。当您使用IDisposable类时,您应该真正使用它。

您也可以不使用System.Drawing. 为此,我在 Magick.NET 的文档中创建了一个新示例:https ://magick.codeplex.com/wikipage?title=Watermark&referringTitle=Documentation

您可以在您的情况下使用以下代码:

using (MagickImage image = new MagickImage(response))
{
  MagickGeometry size = new MagickGeometry(imgWidth, imgHeight);
  size.IgnoreAspectRatiomaintainAspectRatio;                                   
  image.Resize(size);

  using (MagickImage watermark = new MagickImage("G:/Images/watermark.png"))
  {
    image.Composite(watermark, image.Width - 118, image.Height - 29, CompositeOperator.Over);
    image.Write("G:/Images/ProcessedImage.JPG");
  }
}
于 2015-08-01T11:14:12.787 回答