C# SixLabors.ImageSharp.Drawing的多种用途

发布时间:2023年12月21日

在这里插入图片描述

生成验证码

/// <summary>
/// 生成二维码
/// </summary>
/// <param name="webRootPath">wwwroot目录</param>
/// <param name="verifyCode">验证码</param>
/// <param name="width">图片宽度</param>
/// <param name="height">图片高度</param>
/// <returns></returns>
public static byte[] CreateByteByImgVerifyCode(string webRootPath, string verifyCode, int width = 120, int height = 50)
{
   using Image image = new Image<Rgba32>(width, height);
   //漆底色白色
   image.Mutate(x => x.DrawLine(Pens.DashDot(Color.White, width), new PointF[] { new PointF() { X = 0, Y = 0 }, new PointF() { X = width, Y = height } }));

   FontCollection collection = new();
   FontFamily family = collection.Add(Path.Combine(webRootPath, "fonts", "FZHTJW.TTF"));
   Font font = family.CreateFont(20, FontStyle.Bold);

   PointF startPointF = new PointF(5, 5);
   Random random = new Random(); //随机数产生器

   Color[] colors = new Color[] { Color.Red, Color.Blue, Color.Green, Color.Purple, Color.Peru, Color.LightSeaGreen, Color.Lime, Color.Magenta, Color.Maroon, Color.MediumBlue, Color.MidnightBlue, Color.Navy };
   //绘制大小
   for (int i = 0; i < verifyCode.Length; i++)
   {
       image.Mutate(x => x.DrawText(verifyCode[i].ToString(), font, colors[random.Next(colors.Length)], startPointF));
       startPointF.X += (int)(width - 10) / verifyCode.Length;
       startPointF.Y = random.Next(5, 10);
   }

   var pen = Pens.DashDot(Color.Silver, 1);

   //绘制干扰线
   for (var k = 0; k < 30; k++)
   {
       PointF[] points = new PointF[2];
       points[0] = new PointF(random.Next(width), random.Next(height));
       points[1] = new PointF(random.Next(width), random.Next(height));
       image.Mutate(x => x.DrawLine(pen, points));
   }
   using MemoryStream stream = new MemoryStream();
   image.Save(stream, PngFormat.Instance);
   //输出图片流  
   return stream.ToArray();
}
    

压缩图片


/// <summary>
/// 生成缩略图并保存
/// </summary>
/// <param name="sFile">原图路径</param>
/// <param name="dFile">生成的缩略图路径</param>
/// <param name="dHeight">缩略图高度</param>
/// <param name="dWidth">缩略图宽度</param>
/// <param name="flag">压缩质量1-100</param>
/// <returns></returns>
public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag)
{
    Image sourceImage = null;
    FileStream compressImageFile = null;
    try
    {
        sourceImage = Image.Load(sFile);
        if (sourceImage == null)
        {
            return false;
        }
        var originWidth = sourceImage.Width;
        var originHeight = sourceImage.Height;
        if (dWidth <= 0 && dHeight <= 0)
        {
            //如果都是0就是原图
            dWidth = originWidth;
            dHeight = originHeight;
        }
        int sW;
        int sH;
        //按比例缩放
        if (originWidth > dWidth || originHeight > dHeight)
        {
            if ((originWidth * dHeight) > (originHeight * dWidth))
            {
                sW = dWidth;
                sH = (dWidth * originHeight) / originWidth;
            }
            else
            {
                sH = dHeight;
                sW = (originWidth * dHeight) / originHeight;
            }
        }
        else
        {
            sW = originWidth;
            sH = originHeight;
        }
        缩放并且换转为灰度图
        //image.Mutate(x => x
        //         .Resize(image.Width / 2, image.Height / 2)  // 缩放
        //         .Grayscale());  // 转灰度图
        sourceImage.Mutate(x => x.Resize(sW, sH));
        //获取编码器
        var iamgeFormat = sourceImage.Metadata.DecodedImageFormat;
        IImageEncoder encoder = null;
        switch (iamgeFormat.Name.ToLower())
        {
            case "png":
            case "gif":
            case "bmp":
                break;
            default:
                encoder = new JpegEncoder()
                {
                    Quality = flag //Use variable to set between 5-30 based on your requirements
                };
                break;
        }
        compressImageFile = new FileStream(dFile, FileMode.CreateNew, FileAccess.Write);
        if(encoder!=null)
        {
            sourceImage.Save(compressImageFile, encoder);
        }
        else
        {
            sourceImage.Save(compressImageFile, iamgeFormat);
        }
        return true;
    }
    catch
    {
        return false;
    }
    finally
    {
        compressImageFile?.Dispose();
        sourceImage?.Dispose();
    }
}

/// <summary>
/// 生成缩略图并返回byte数组
/// </summary>
/// <param name="sFile">原图路径</param>
/// <param name="dHeight">缩略图高度</param>
/// <param name="dWidth">缩略图宽度</param>
/// <param name="flag">压缩质量1-100</param>
/// <returns></returns>
public static byte[]? GetPicThumbnail(string sFile, int dHeight, int dWidth, int flag)
{
    Image sourceImage = null;
    MemoryStream compressImageFile = null;
    try
    {
        sourceImage = Image.Load(sFile);
        if (sourceImage == null)
        {
            return null;
        }
        var originWidth = sourceImage.Width;
        var originHeight = sourceImage.Height;
        if (dWidth <= 0 && dHeight <= 0)
        {
            //如果都是0就是原图
            dWidth = originWidth;
            dHeight = originHeight;
        }
        int sW;
        int sH;
        //按比例缩放
        if (originWidth > dWidth || originHeight > dHeight)
        {
            if ((originWidth * dHeight) > (originHeight * dWidth))
            {
                sW = dWidth;
                sH = (dWidth * originHeight) / originWidth;
            }
            else
            {
                sH = dHeight;
                sW = (originWidth * dHeight) / originHeight;
            }
        }
        else
        {
            sW = originWidth;
            sH = originHeight;
        }
        sourceImage.Mutate(x => x.Resize(sW, sH));
        //获取编码器
        //获取编码器
        var iamgeFormat = sourceImage.Metadata.DecodedImageFormat;
        IImageEncoder encoder = null;
        switch (iamgeFormat.Name.ToLower())
        {
            case "png":
            case "gif":
            case "bmp":
                break;
            default:
                encoder = new JpegEncoder()
                {
                    Quality = flag //Use variable to set between 5-30 based on your requirements
                };
                break;
        }
        compressImageFile = new MemoryStream();
        if (encoder != null)
        {
            sourceImage.Save(compressImageFile, encoder);
        }
        else
        {
            sourceImage.Save(compressImageFile, iamgeFormat);
        }
        return compressImageFile.ToArray();
    }
    catch
    {
        return null;
    }
    finally
    {
        compressImageFile?.Dispose();
        sourceImage?.Dispose();
    }
}

生成海报

https://blog.csdn.net/qq_36437991/article/details/133383006

生成二维码

还需要依赖于QRCode库
在这里插入图片描述
有一个和image-sharp深度继承的库,它是跨平台的,不过目前最新版的qrcode应该也是跨平台的
在这里插入图片描述

/// <summary>
/// 将二维码转化为base64格式
/// </summary>
/// <param name="content">二维码内容</param>
/// <param name="iconPath">logo图片地址</param>
/// <returns></returns>
public string ToBase64QRCode(string content, string iconPath)
{
    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeData qrCodeData = qrGenerator.CreateQrCode(content, QRCodeGenerator.ECCLevel.H);
    var qrCode = new BitmapByteQRCode(qrCodeData);
    var qrCodeImage = qrCode.GetGraphic(5);
    if (string.IsNullOrEmpty(iconPath))
    {
        var res = Convert.ToBase64String(qrCodeImage);
        return res;
    }
    var iconImg = Image.Load(iconPath);
    iconImg.Mutate(x => x.Resize(60, 60, KnownResamplers.Box));
    var qrcodeImg = Image.Load(qrCodeImage);
    var left = qrcodeImg.Width / 2 - iconImg.Width / 2;
    var top = qrcodeImg.Height / 2 - iconImg.Height / 2;
    qrcodeImg.Mutate(t => t.DrawImage(iconImg, new Point(left, top), 1f));
    var qrcodeStream = new MemoryStream();
    qrcodeImg.Save(qrcodeStream, new PngEncoder());
    return Convert.ToBase64String(qrcodeStream.ToArray());
}
文章来源:https://blog.csdn.net/qq_36437991/article/details/135131451
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。