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

在这里插入图片描述

生成验证码

/// <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());
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/262126.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

互联网加竞赛 python+大数据校园卡数据分析

0 前言 &#x1f525; 优质竞赛项目系列&#xff0c;今天要分享的是 &#x1f6a9; 基于yolov5的深度学习车牌识别系统实现 &#x1f947;学长这里给一个题目综合评分(每项满分5分) 难度系数&#xff1a;4分工作量&#xff1a;4分创新点&#xff1a;3分 该项目较为新颖&am…

德人合科技 | 设计公司文件加密系统——天锐绿盾自动智能透明加密防泄密系统

设计公司文件加密系统——天锐绿盾自动智能透明加密防泄密系统 PC端访问地址&#xff1a; www.drhchina.com 一、背景介绍 设计公司通常涉及到大量的创意作品、设计方案、客户资料等重要文件&#xff0c;这些文件往往包含公司的核心价值和商业机密。因此&#xff0c;如何确保…

@vue/cli脚手架

0_vue/cli 脚手架介绍 目标: webpack自己配置环境很麻烦, 下载vue/cli包,用vue命令创建脚手架项目 vue/cli是Vue官方提供的一个全局模块包(得到vue命令), 此包用于创建脚手架项目 脚手架是为了保证各施工过程顺利进行而搭设的工作平 vue/cli的好处 开箱即用 0配置webpack babe…

个人财务工具、密钥管理平台、在线会计软件、稍后阅读方案 | 开源专题 No.51

gethomepage/homepage Stars: 10.1k License: GPL-3.0 这个项目是一个现代化、完全静态的、快速且安全的应用程序仪表盘&#xff0c;具有超过 100 种服务和多语言翻译的集成。 快速&#xff1a;网站在构建时以静态方式生成&#xff0c;加载时间飞快。安全&#xff1a;所有对后…

全面掌握XSS漏洞攻击,实战案例从Self-XSS到账户接管,以及通过参数污染的XSS实现攻击

全面掌握XSS漏洞攻击,实战案例从Self-XSS到账户接管。 什么是跨站脚本攻击 (XSS)? 跨站脚本攻击(XSS)是一种网络安全漏洞,允许攻击者破坏用户与易受攻击的应用程序之间的交互。它允许攻击者绕过同源策略,该策略旨在将不同的网站隔离开来。XSS漏洞通常允许攻击者伪装成受…

Unity中Shader缩放矩阵

文章目录 前言一、直接相乘缩放1、在属性面板定义一个四维变量&#xff0c;用xyz分别控制在xyz轴上的缩放2、在常量缓存区申明该变量3、在顶点着色器对其进行相乘&#xff0c;来缩放变换4、我们来看看效果 二、使用矩阵乘法代替直接相乘缩放的原理1、我们按如下格式得到缩放矩阵…

【CentOS 7.9 分区】挂载硬盘为LVM操作实例

LVM与标准分区有何区别&#xff0c;如何选择 目录 1 小系统使用LVM的益处&#xff1a;2 大系统使用LVM的益处&#xff1a;3 优点&#xff1a;CentOS 7.9 挂载硬盘为LVM操作实例查看硬盘情况格式化硬盘创建PV创建VG创建LV创建文件系统并挂载自动挂载添加&#xff1a;注意用空格间…

Asp.Net Core 项目中常见中间件调用顺序

常用的 AspNetCore 项目中间件有这些&#xff0c;调用顺序如下图所示&#xff1a; 最后的 Endpoint 就是最终生成响应的中间件。 Configure调用如下&#xff1a; public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseD…

HTTPS攻击是什么?应该如何应对

近期越来越多的站长以及企业网站负责人有联系反馈说最近HTTPS攻击越来越频繁&#xff0c;让业务无法正常开展从而来寻求解决方法。随着互联网的普及和电子商务的发展&#xff0c;HTTPS协议在保障网络安全方面发挥着越来越重要的作用。然而&#xff0c;HTTPS协议并非完全安全&am…

pytorch-模型预测概率值为负数

在进行ocr识别模型预测的时候&#xff0c;发现预测的结果是正确的&#xff0c;但是概率值是负数&#xff1a; net_out net(img) #torch.Size([70, 1, 41]) logit, preds net_out.max(2) #41是类别 需要对类别取最大值 preds preds.transpose(1, 0).contiguous().view(-1) …

three.js实战模拟VR全景视图

文章中使用到的案例图片都来源于&#xff1a;Humus - Textures 里面有很多免费的资源&#xff0c;可以直接下载&#xff0c;每个资源里面都提供6个不同方位的图片&#xff0c;我们通过threejs稍微处理一下&#xff0c;就能实现以下3D效果的场景了。 <template><div …

AI Native工程化:百度App AI互动技术实践

作者 | GodStart 导读 随着AI浪潮的兴起&#xff0c;越来越多的应用都在利用大模型重构业务形态&#xff0c;在设计和优化Prompt的过程中&#xff0c;我们发现整个Prompt测评和优化周期非常长&#xff0c;因此&#xff0c;我们提出了一种Prompt生成、评估与迭代的一体化解决方案…

BearPi Std 板从入门到放弃 - 后天篇(3)(ESP8266透传点灯)

简介 电脑搭建一个TCP Server&#xff0c; ESP8266 串口设置好透传模式, 再由TCP Server发送指令控制灯的亮灭; 开灯指令&#xff1a; led_on回车 &#xff1b; 关灯指令: led_off回车 主芯片: STM32L431RCT6 LED : PC13 \ 推挽输出即可 \ 高电平点亮 串口: Usart1 / LPUART E…

Flink电商实时数仓(三)

DIM层代码流程图 维度层的重点和难点在于实时电商数仓需要的维度信息一般是动态的变化的&#xff0c;并且由于实时数仓一般需要一直运行&#xff0c;无法使用常规的配置文件重启加载方式来修改需要读取的ODS层数据&#xff0c;因此需要通过Flink-cdc实时监控MySql中的维度数据…

开发医疗陪诊系统源码:搭建安全高效的医患互动平台

本文将深入探讨开发医疗陪诊系统的源码&#xff0c;以及如何搭建一个安全高效的医患互动平台。 一、引言 医疗陪诊系统旨在通过技术手段&#xff0c;缩短患者与医生之间的距离&#xff0c;提供更快速、便捷的医疗服务。 二、技术选型 2.1前端技术 在搭建医疗陪诊系统的前…

Redis-Day3实战篇-商户查询缓存(缓存的添加和更新, 缓存穿透/雪崩/击穿, 缓存工具封装)

Redis-Day3实战篇-商户查询缓存 什么是缓存添加Redis缓存业务流程项目实现练习 - 给店铺类型查询业务添加缓存 缓存更新策略最佳实践方案案例 - 给查询商铺的缓存添加超时剔除和主动更新 缓存穿透/雪崩/击穿缓存穿透概述项目实现 - 商铺查询缓存 缓存雪崩缓存击穿概述互斥锁逻辑…

HBase基础知识(二):HBase集群部署、HBaseShell操作

1. HBase安装部署 1.1 Zookeeper正常部署 首先保证Zookeeper集群的正常部署&#xff0c;并启动之&#xff1a; 创建集群启动脚本&#xff1a; #!/bin/bash case $1 in "start"){ for i in hadoop100 hadoop101 hadoop102 do echo----------zookeeper $i 启动----…

vue2 之 实现pdf电子签章

一、前情提要 1. 需求 仿照e签宝&#xff0c;实现pdf电子签章 > 拿到pdf链接&#xff0c;移动章的位置&#xff0c;获取章的坐标 技术 : 使用fabric pdfjs-dist vuedraggable 2. 借鉴 一位大佬的代码仓亏 : 地址 一位大佬写的文章 &#xff1a;地址 3. 优化 在大佬的代码…

【算法与数据结构】135、LeetCode分发糖果

文章目录 一、题目二、解法三、完整代码 所有的LeetCode题解索引&#xff0c;可以看这篇文章——【算法和数据结构】LeetCode题解。 一、题目 二、解法 思路分析&#xff1a;本题的思路是要相比较一边&#xff0c;然后在比较另外一边&#xff0c;左右两边一起比较的代码非常难写…

​ SK Ecoplant借助亚马逊云科技,海外服务器为环保事业注入新活力

在当今全球面临着资源紧缺和环境挑战的大背景下&#xff0c;数字技术所依赖的海外服务器正成为加速循环经济转型的关键利器。然而&#xff0c;很多企业在整合数字技术到运营中仍然面临着一系列挑战&#xff0c;依然存在低效流程导致的不必要浪费。针对这一问题&#xff0c;SK E…