Better method instance code of generating watermark by. Net

Time:2020-6-16

preface

As we all know, in order to protect intellectual property rights and prevent resources from being stolen, watermarks are very common in blogs, online stores and other scenes.

This article first demonstrates theSystem.Drawing.ImageDo normal operation. Then based on direct2d / WIC / directwrite, a new and different “Sao” operation is demonstrated.

Method 1- System.Drawing Watermark a picture

System.Drawing.ImageNative is part of GDI, windows only, but with nuget packageSystem.Drawing.CommonNowSystem.Drawing.ImageLinux is already supported:


Install-Package System.Drawing.Common -Version 4.5.1

The following code shows how to watermark an image from:

//Add watermark
var watermarkedStream = new MemoryStream();
using (var img = Image.FromStream(File.OpenRead(@"D:\_\WatermarkDemo.png")))
{
 using (var graphic = Graphics.FromImage(img))
 {
  Var font = new font ("Microsoft YaHei", 30, FontStyle.Bold , GraphicsUnit.Pixel );
  var color = Color.FromArgb(128, 255, 255, 255);
  var brush = new SolidBrush(color);
  var point = new Point(img.Width - 130, img.Height - 50);

  graphic.DrawString ("watermark here", font, brush, point);
  img.Save(watermarkedStream, ImageFormat.Png);
 }
}

The effect is as shown in the figure (without yellow cutting head):

Attached: Edi.Wang Make a nuget package to easily configure watermark parameters:

NuGet:https://github.com/EdiWang/Edi.ImageWatermark

article: https://edi.wang/post/2018/10/12/add-watermark-to-uploaded-image-aspnet-core

Method 2-direct2d / WIC watermark image

Direct2d comes from Windows 8 / IE 10. After ie 10 is installed, Windows 7 can also be used. Direct2d is based on Direct3D, which is obviously windows only.

Direct2d is the next generation of windows 2d rendering library. With the release of direct2d, there are windows imaging component (WIC) and directwrite.

Related instructions and document links:

technology explain link
Direct2D 2D graphics rendering based on hardware acceleration Go
WIC High performance picture coding and decoding Go
DirectWrite Text rendering based on hardware acceleration Go

If you take a look at the links, it’s not hard to see that these technologies are com based, but we use. Net, right?

Fortunately, we have sharpdx

Sharpdx encapsulates these DirectX technologies. In this demo, we need to install SharpDX.Direct2D1 and SharpDX.Mathematics Two packages:


Install-Package SharpDX.Direct2D1 -Version 4.2.0
Install-Package SharpDX.Mathematics -Version 4.2.0

The following code shows how to use SharpDX.Direct2D1 Watermark image:

using D2D = SharpDX.Direct2D1;
using DWrite = SharpDX.DirectWrite;
using SharpDX;
using SharpDX.IO;
using WIC = SharpDX.WIC;

MemoryStream AddWatermark(Stream fileName, string watermarkText)
{
  using (var wic = new WIC.ImagingFactory2())
  using (var d2d = new D2D.Factory())
  using (var image = CreateWicImage(wic, fileName))
  using (var wicBitmap = new WIC.Bitmap(wic, image.Size.Width, image.Size.Height, WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnDemand))
  using (var target = new D2D.WicRenderTarget(d2d, wicBitmap, new D2D.RenderTargetProperties()))
  using (var bmpPicture = D2D.Bitmap.FromWicBitmap(target, image))
  using (var dwriteFactory = new SharpDX.DirectWrite.Factory())
  using (var brush = new D2D.SolidColorBrush(target, new Color(0xff, 0xff, 0xff, 0x7f)))
  {
    target.BeginDraw();
    {
      target.DrawBitmap(bmpPicture, new RectangleF(0, 0, target.Size.Width, target.Size.Height), 1.0f, D2D.BitmapInterpolationMode.Linear);
      target.DrawRectangle(new RectangleF(0, 0, target.Size.Width, target.Size.Height), brush);
      var textFormat = new  DWrite.TextFormat (dwritefactory, "Microsoft YaHei", DWrite.FontWeight.Bold , DWrite.FontStyle.Normal , 30.0f);
      target.DrawText(watermarkText, textFormat, new RectangleF(target.Size.Width - 130, target.Size.Height - 50, int.MaxValue, int.MaxValue), brush);
    }
    target.EndDraw();

    var ms = new MemoryStream();
    SaveD2DBitmap(wic, wicBitmap, ms);
    return ms;
  }
}

void SaveD2DBitmap(WIC.ImagingFactory wicFactory, WIC.Bitmap wicBitmap, Stream outputStream)
{
  using (var encoder = new WIC.BitmapEncoder(wicFactory, WIC.ContainerFormatGuids.Png))
  {
    encoder.Initialize(outputStream);
    using (var frame = new WIC.BitmapFrameEncode(encoder))
    {
      frame.Initialize();
      frame.SetSize(wicBitmap.Size.Width, wicBitmap.Size.Height);

      var pixelFormat = wicBitmap.PixelFormat;
      frame.SetPixelFormat(ref pixelFormat);
      frame.WriteSource(wicBitmap);

      frame.Commit();
      encoder.Commit();
    }
  }
}

WIC.FormatConverter CreateWicImage(WIC.ImagingFactory wicFactory, Stream stream)
{
  using (var decoder = new WIC.PngBitmapDecoder(wicFactory))
  {
    var decodeStream = new WIC.WICStream(wicFactory, stream);
    decoder.Initialize(decodeStream, WIC.DecodeOptions.CacheOnLoad);
    using (var decodeFrame = decoder.GetFrame(0))
    {
      var converter = new WIC.FormatConverter(wicFactory);
      converter.Initialize(decodeFrame, WIC.PixelFormat.Format32bppPBGRA);
      return converter;
    }
  }
}

Call method:

File.WriteAllBytes (@"D:\_ \Demo2.png", AddWatermark( File.OpenRead (@"D:\_ " WatermarkDemo.png ")," watermark here "). Toarray());

The effect is also normal:

What’s the difference?

System.Drawing It only takes 14 lines, but direct2d needs 60 lines! Amazing complexity! Why do we have to give up simplicity and seek complexity?

because System.Drawing There is no hardware acceleration, and the generated images are not anti aliasing, which leads to the use ofSystem.DrawingIn contrast, it is slower, and the effect of generating pictures is slightly worse:

It’s clear that direct2d produces smoother images.

summary

The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer.