How to add watermarking instance code to upload image function in ASP.NET Core

Time:2019-10-2

Preface

For some reasons, we need to add text watermarking and image watermarking to the picture, so here we make a simple record. Let’s see the detailed implementation process.

Method of realization:

In the traditional. NET framework, we add watermarks to images either through HttpModules or HttpHandler. Then we can add watermarks through the following code:


var image = new WebImage(imageBytes);
image.AddTextWatermark(
 Settings.Instance.WatermarkText, "White", Settings.Instance.WatermarkFontSize,
 opacity: Settings.Instance.WatermarkTextOpacityPercentage
);

But you are not allowed to do this in. NET Core because there is no WebImage type. In today’s. NET Core, we upload files through IFormFile, which contains many formats. Let’s try it.

First of all, we must know where we want to save the picture. We need the most basic constructor in the.NET Core to get the project directory.


public readonly ILogger<ImageController> Logger = null;
 private IHostingEnvironment hostingEnv;
 public ImageController(ILogger<ImageController> logger,IHostingEnvironment env)
 {
  Logger = logger;
  this.hostingEnv = env;
 }

Because we can expand the use of simple log frameworks, we can also construct the log framework of that set. NET Core add watermarking code can be written like this.


// Add watermark
    var watermarkedStream = new MemoryStream();
    using (var img = Image.FromStream(stream))
    {
    using (var graphic = Graphics.FromImage(img))
    {
     var font = new Font(FontFamily.GenericSansSerif, 20, FontStyle.Bold, GraphicsUnit.Pixel);
     var color = Color.FromArgb(128, 255, 255, 255);
     var brush = new SolidBrush(color);
     var point = new Point(img.Width - 120, img.Height - 30);

     graphic.DrawString("cnblogs.com/zaranet", font, brush, point);
     img.Save(watermarkedStream, ImageFormat.Png);
    }
    img.Save(hostingEnv.WebRootPath+"/"+name);
    }

Here we change the memory that we pass in to Image, or Bitmap, and then we go through the graphics class method and turn it into a modifiable graphics type, with more than 200 methods. That’s drawing.~

The complete code is as follows:


[HttpPost]
 public async Task<IActionResult> UploadImageAsync(IFormFile file)
 {
  try
  {
  if (null == file)
  {
   Logger.LogError("file is null.");
   return BadRequest();
  }

  if (file.Length > 0)
  {
   var name = Path.GetFileName(file.FileName);
   if (name != null)
   {
   using (var stream = new MemoryStream())
   {
    await file.CopyToAsync(stream);

    // Add watermark
    var watermarkedStream = new MemoryStream();
    using (var img = Image.FromStream(stream))
    {
    using (var graphic = Graphics.FromImage(img))
    {
     var font = new Font(FontFamily.GenericSansSerif, 20, FontStyle.Bold, GraphicsUnit.Pixel);
     var color = Color.FromArgb(128, 255, 255, 255);
     var brush = new SolidBrush(color);
     var point = new Point(img.Width - 120, img.Height - 30);

     graphic.DrawString("cnblogs.com/zaranet", font, brush, point);
     img.Save(watermarkedStream, ImageFormat.Png);
    }
    img.Save(hostingEnv.WebRootPath+"/"+name);

    }
    return StatusCode(StatusCodes.Status200OK);
   }
   }
  }
  return BadRequest();
  }
  catch (Exception e)
  {
  Logger.LogError(e, $"Error uploading image.");
  return StatusCode(StatusCodes.Status500InternalServerError);
  }
 }

Finally, you can use PostMan for testing.

Key is the name of your parameter, and the picture ends up like this.

summary

The above is the whole content of this article. I hope that the content of this article will have some reference and learning value for everyone’s study or work. If there is any doubt, you can leave a message to exchange. Thank you for your support for developpaer.