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

C# SixLabors.ImageSharp.Drawing的多种用途_第1张图片

生成验证码

/// 
/// 生成二维码
/// 
/// wwwroot目录
/// 验证码
/// 图片宽度
/// 图片高度
/// 
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();
}
    

压缩图片


/// 
/// 生成缩略图并保存
/// 
/// 原图路径
/// 生成的缩略图路径
/// 缩略图高度
/// 缩略图宽度
/// 压缩质量1-100
/// 
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();
    }
}

/// 
/// 生成缩略图并返回byte数组
/// 
/// 原图路径
/// 缩略图高度
/// 缩略图宽度
/// 压缩质量1-100
/// 
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库
C# SixLabors.ImageSharp.Drawing的多种用途_第2张图片
有一个和image-sharp深度继承的库,它是跨平台的,不过目前最新版的qrcode应该也是跨平台的
C# SixLabors.ImageSharp.Drawing的多种用途_第3张图片

/// 
/// 将二维码转化为base64格式
/// 
/// 二维码内容
/// logo图片地址
/// 
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());
}

你可能感兴趣的:(dotnet,c#,开发语言)