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

随心笔谈12个月前发布 admin
90 0

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);

}
}
}

© 版权声明

相关文章