.NetCore如何使用ImageSharp进行图片的生成

    ImageSharp是对NetCore平台扩展的一个图像处理方案,以往网上的案例多以生成文字及画出简单图形、验证码等方式进行探讨和实践。

    今天我分享一下所在公司项目的实际应用案例,导出微信二维码图片,圆形头像等等。

一、源码获取

    Git项目地址:https://github.com/SixLabors/ImageSharp

    安装这两个包即可:

    Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0001 

    Install-Package SixLabors.ImageSharp.Drawing -Version 1.0.0-beta0001 

二、应用

    1.在图片中画出文字

     首先要注意字体问题,Windows自带的字体一般存储于 C:\Windows\Fonts 文件夹内,如果是部署在Linux系统的应用程序,则存储于 usr/share/fonts 文件夹内。以黑体为例,我们找到对应的字体文件 SIMHEI.TTF ,将其放入项目的根目录内方便调用。

 

 1   var path = "Image/Mud.png"                                  //图片路径
 2   FontCollection fonts = new FontCollection();
 3   FontFamily fontfamily = fonts.Install("Source/SIMHEI.TTF"); //字体的路径
var font = new Font(fontfamily,50); 4 using (Image<Rgba32> image = Image.Load(path)) 5 { 6 image.Mutate(x => x.
DrawText (
8 "陆家嘴旗舰店", //文字内容 9 font, 10 Rgba32.Black, //文字颜色 11 new PointF(100,100)) //坐标位置(浮点) 12 ); 13 image.Save(path); 14 }

 

       关于Image.Load()获取图片方法的使用,可以直接读取Stream类型的流,也可以根据图片的本地路径获取。

//线上地址的图片,通过获取流的方式读取   
WebRequest imgRequest = WebRequest.Create(url);
var res = (HttpWebResponse)imgRequest.GetResponse();
var image  = Image.Load(res.GetResponseStream());

      获取文字的像素宽度,可以使用:

  var str = "我是什么长度"  var size = TextMeasurer.Measure(str, new RendererOptions(new Font(fontfamily,50)));
var width = size.Width;

 

 

      2.在图片中画出圆形的头像

      我在ImageSharp的源码中,发现有画圆形的工具类可以使用,在这里直接copy出来。

 1 using SixLabors.ImageSharp;
 2 using SixLabors.ImageSharp.PixelFormats;
 3 using SixLabors.ImageSharp.Processing;
 4 using SixLabors.Primitives;
 5 using SixLabors.Shapes;
 6 using System;
 7 using System.Collections.Generic;
 8 using System.Text;
 9 
10 namespace CodePicDownload
11 {
12     public static class CupCircularHelper
13     {
14 
15         public static IImageProcessingContext<Rgba32> ConvertToAvatar(this IImageProcessingContext<Rgba32> processingContext, Size size, float cornerRadius)
16         {
17             return processingContext.Resize(new ResizeOptions
18             {
19                 Size = size,
20                 Mode = ResizeMode.Crop
21             }).Apply(i => ApplyRoundedCorners(i, cornerRadius));
22         }
23 
24 
25         // This method can be seen as an inline implementation of an `IImageProcessor`:
26         // (The combination of `IImageOperations.Apply()` + this could be replaced with an `IImageProcessor`)
27         private static void ApplyRoundedCorners(Image<Rgba32> img, float cornerRadius)
28         {
29             IPathCollection corners = BuildCorners(img.Width, img.Height, cornerRadius);
30 
31             var graphicOptions = new GraphicsOptions(true)
32             {
33                 AlphaCompositionMode = PixelAlphaCompositionMode.DestOut // enforces that any part of this shape that has color is punched out of the background
34             };
35             // mutating in here as we already have a cloned original
36             // use any color (not Transparent), so the corners will be clipped
37             img.Mutate(x => x.Fill(graphicOptions, Rgba32.LimeGreen, corners));
38         }
39 
40         private static IPathCollection BuildCorners(int imageWidth, int imageHeight, float cornerRadius)
41         {
42             // first create a square
43             var rect = new RectangularPolygon(-0.5f, -0.5f, cornerRadius, cornerRadius);
44 
45             // then cut out of the square a circle so we are left with a corner
46             IPath cornerTopLeft = rect.Clip(new EllipsePolygon(cornerRadius - 0.5f, cornerRadius - 0.5f, cornerRadius));
47 
48             // corner is now a corner shape positions top left
49             //lets make 3 more positioned correctly, we can do that by translating the orgional artound the center of the image
50 
51             float rightPos = imageWidth - cornerTopLeft.Bounds.Width + 1;
52             float bottomPos = imageHeight - cornerTopLeft.Bounds.Height + 1;
53 
54             // move it across the width of the image - the width of the shape
55             IPath cornerTopRight = cornerTopLeft.RotateDegree(90).Translate(rightPos, 0);
56             IPath cornerBottomLeft = cornerTopLeft.RotateDegree(-90).Translate(0, bottomPos);
57             IPath cornerBottomRight = cornerTopLeft.RotateDegree(180).Translate(rightPos, bottomPos);
58 
59             return new PathCollection(cornerTopLeft, cornerBottomLeft, cornerTopRight, cornerBottomRight);
60         }
61   }
62 }

           有了画圆形的方法,我们只需要调用ConvertToAvatar() 方法把方形的图片转为圆形,画在图片上即可。

1 using (Image<Rgba32> image = Image.Load("Image/Mud.png"))
2 {
3     var logoWidth = 300;
4     var logo = Image.Load("Image/Logo.png")
5 logo.Mutate(x => x.ConvertToAvatar(new Size(logoWidth, logoWidth), logoWidth / 2)); 6 image.Mutate(x => x.DrawImage(logo, new Point(100, 100), 1)); 7 Image.Save("..");
8 }

 

 

  3.处理二维码的BitMatrix类型

   我以微信获取的二维码类型为例,因为我的项目中二维码是从微信公众号平台API获取,在这次获取图片中,将BitMatrix类型转换为流的格式从而可以通过Image.Load()方法获取图片信息成为了关键。在这里我还是引用到了System.Drawing,可以单独提取公用方法。

 

 1         public void WriteToStream(BitMatrix QrMatrix, ImageFormat imageFormat, Stream stream)
 2         {
 3             if (imageFormat != ImageFormat.Exif && imageFormat != ImageFormat.Icon && imageFormat != ImageFormat.MemoryBmp)
 4             {
 5                 DrawingSize size = m_iSize.GetSize(QrMatrix?.Width ?? 21);
 6                 using (Bitmap bitmap = new Bitmap(size.CodeWidth, size.CodeWidth))
 7                 {
 8                     using (Graphics graphics = Graphics.FromImage(bitmap))
 9                     {
10                         Draw(graphics, QrMatrix);
11                         bitmap.Save(stream, imageFormat);
12                     }
13                 }
14             }
15         }

 

       这样数据就存入了stream中,但直接用ImageSharp去Load处理过的流可能会有些问题,为了保险,我将数据流中的byte取出,实例化了一个新的MemoryStream类型。这样,就可以获取到二维码的图片了。

1 //Matrix为BitMatrix类型数据,ImageFormat我选择了png类型
2 MemoryStream ms = new MemoryStream();   
3 WriteToStream(Matrix,System.Drawing.Imaging.ImageFormat.Png, ms);
4 byte[] data = new byte[ms.Length];
5 ms.Seek(0, SeekOrigin.Begin);
6 ms.Read(data, 0, Convert.ToInt32(ms.Length));
7 var image =  Image.Load(new MemoryStream(data));

 

      最后附上保存后图片的效果:

 

      本篇内容到此就结束了,非常感谢您的观看,有机会的话,希望能够一起讨论技术,一起成长!

 

转载于:https://www.cnblogs.com/niwan/p/11126239.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用ZXing.ImageSharp.V2组件生成二维码图片,并在图片上包含二维码和提示文字时,并且要求兼容Linux系统,你可以按照以下步骤进行操作: 首先,确保你的项目中已安装了ZXing.Net库和ImageSharp库,可以通过NuGet包管理器进行安装。 接下来,你可以使用以下代码方法来生成带有二维码和提示文字的图片: ```csharp using System; using System.IO; using System.Text; using SixLabors.Fonts; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Processing; using ZXing; using ZXing.Common; public class QrCodeGenerator { public static void GenerateQrCodeWithText(string content, string text, string outputPath) { // 生成二维码 BarcodeWriter writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new EncodingOptions { Width = 300, Height = 300 } }; using (var qrCodeImage = writer.Write(content)) { // 加载字体 var fontCollection = new FontCollection(); var font = fontCollection.Install("path/to/your/font.ttf"); // 创建画布 var image = new Image<Rgba32>(500, 500); image.Mutate(ctx => { ctx.Fill(Rgba32.White); ctx.DrawImage(qrCodeImage, new Point(100, 100), 1f); ctx.DrawText(new TextGraphicsOptions { TextOptions = new TextOptions { FontSize = 24, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Bottom, ApplyKerning = true }, WrapTextWidth = 300 }, text, font, Rgba32.Black, new PointF(250, 400)); }); // 保存图片 image.Save(outputPath); } } } ``` 在上述代码中,你需要将`"path/to/your/font.ttf"`替换为你自己的字体文件路径。此外,你可以根据需要调整二维码的大小、文字的大小和位置等参数。 最后,调用该方法并传入相应的参数即可生成带有二维码和提示文字的图片: ```csharp string content = "Your content here"; string text = "Your text here"; string outputPath = "path/to/output/image.png"; QrCodeGenerator.GenerateQrCodeWithText(content, text, outputPath); ``` 请注意,该方法需要在支持ImageSharp和ZXing.Net的环境中运行,因此确保已将这些库安装到你的项目中,并引入相关命名空间。 希望以上代码能满足你的需求,如果有任何问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值