欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-04 11:39:16
ImageSharp是对NetCore平台扩展的一个图像处理方案,以往网上的案例多以生成文字及画出简单图形、验证码等方式进行探讨和实践。 今天我分享一下所在公司项目的实际应用案例,导出微信二维码图片,圆形头像等等。 一、源码获取 Git项目地址:https://github.com/SixLabor ......

    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"); //字体的路径
 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));

 

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

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

 

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