.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));

 

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

 

      本篇內容到此就結束了,非常感謝您的觀看,有機會的話,希望能夠一起討論技術,一起成長!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM