Content

.NET6使用ImageSharp实现给图片添加水印

文章摘要

本文介绍了一个名为`ImageSharpExtension`的C#类及其静态方法`ApplyScalingImageWaterMark`。该方法用于在图像上添加缩放后的水印,并根据指定位置将其放置在图像上。具体实现如下: 1. **水印缩放处理**:当水印图片的尺寸大于目标图像尺寸时,会根据目标图像的宽高比对水印图片进行缩放。缩放方式分为两种:若目标图像为横向长方形,则水印宽度缩为一半,高度相应调整;若为纵向长方形,则水印高度缩为一半,宽度相应调整。 2. **水印位置设置**:支持多种位置选项,如左上、右下、中心等。根据`waterPosition`参数,可以自定义水印的放置位置。 3. **透明度设置**:通过浮点数`opacity`(默认为0.8)设置水印的透明度,0-1之间值决定了水印的可见性。 该方法结合缩放、位置设置和透明度控制,实现了一种灵活且易用的水印添加功能。

public static class ImageSharpExtention { public static IImageProcessingContext ApplyScalingImageWaterMark(this IImageProcessingContext processingContext, string waterPosition=”center”,string waterPath) { using (var mark_image=SixLabors.ImageSharp.Image.Load(waterPath)) { int markWidth=mark_image.Width; int markHeight=mark_image.Height; var imgSize=processingContext.GetCurrentSize(); if (markWidth >=imgSize.Width || markHeight >=imgSize.Height) //对水印图片进行缩放 { if (imgSize.Width > imgSize.Height)//横的长方形 { markWidth=imgSize.Width / 2; //宽缩放一半 markHeight=(markWidth * imgSize.Height) / imgSize.Width; } else { markHeight=imgSize.Height / 2; markWidth=(markHeight * imgSize.Width) / imgSize.Height; } mark_image.Mutate(mk=> mk.Resize(markWidth, markHeight)); } //水印图片完成成立,开始根据位置添加水印 var position=waterPosition; if (string.IsNullOrEmpty(position)) { position=”center”; } position=position.ToLower(); if (string.IsNullOrEmpty(position)) { position=”center”; } SixLabors.ImageSharp.Point point=new SixLabors.ImageSharp.Point(); //左上 if (position.Contains(“lefttop”)) { point.X=10; point.Y=10; } //上中 if (position.Contains(“topcenter”)) { point.X=(imgSize.Width – mark_image.Width) / 2; point.Y=10; } //右上 if (position.Contains(“righttop”)) { point.X=(imgSize.Width – mark_image.Width) – 10; point.Y=10; } //右中 if (position.Contains(“rightcenter”)) { point.X=(imgSize.Width – mark_image.Width) – 10; point.Y=(imgSize.Height – mark_image.Height) / 2; } //右下 if (position.Contains(“rightbottom”)) { point.X=(imgSize.Width – mark_image.Width) – 10; point.Y=(imgSize.Height – mark_image.Height) – 10; } //下中 if (position.Contains(“bottomcenter”)) { point.X=(imgSize.Width – mark_image.Width) / 2; point.Y=(imgSize.Height – mark_image.Height) – 10; } //左下 if (position.Contains(“leftbottom”)) { point.X=10; point.Y=(imgSize.Height – mark_image.Height) – 10; } //左中 if (position.Contains(“leftcenter”)) { point.X=10; point.Y=(imgSize.Height – mark_image.Height) / 2; } if (position.Contains(“center”)) { point.X=(imgSize.Width – mark_image.Width) / 2; point.Y=(imgSize.Height – mark_image.Height) / 2; } float opacity=(float)0.8;//设置不透明度,0-1之间 //添加水印 return processingContext.DrawImage(mark_image,point,opacity); } } }