.NetCore如何使用ImageSharp進行圖片的生成

来源:https://www.cnblogs.com/niwan/archive/2019/07/03/11126239.html
-Advertisement-
Play Games

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

 

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

 

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

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 題目描述 在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。例如:下麵的二維數組就是每行、每列都遞增排序。如果在這個數組中查找數字7,則返回true;如果查找 ...
  • 命令執行位置:工具=〉Nuget包管理器=〉程式包管理器控制台 一、安裝 1.安裝指定版本類庫install-package <程式包名> -version <版本號> 2.安裝到指定的項目install-package <程式包名> -project XXXProjectName -version ...
  • Array類 a) IEumerable介面是由foreach語句用於迭代數組的介面。 b) ICollection介面派生於IEumerable介面,這個介面主要用於確定集合中的元素個數,或用於同步。 c) IList介面派生於ICollection介面,Array類實現IList介面的主要原因是 ...
  • 在 asp.net core 中全局異常處理,有時候可能不能滿足我們的需要,可能就需要自己自定義一個中間件處理了,最近遇到一個問題,有一些異常,不希望記錄錯誤日誌,目前主要是用戶請求取消導致的 `TaskCanceledException` 和 `OperationCanceledException... ...
  • 前段時間我一直在研究PIE SDK與Python的結合,因為在我的開發中,我想獲取一張圖片的統計直方圖,雖然在SDK中有提供關於直方圖的類介面(如IStatsHistogram 介面、HistogramStatDialog 類),但其中有些方法得到的結果數據是有些小問題的(已經向技術人員反應),所以 ...
  • 先 NuGet兩個程式集 1:MongoDB.Driver、 2:MongoDB.Bson namespace ConsoleApp1{ /// <summary> /// MongoDb幫助類 /// </summary> /// <summary> /// MongoDb幫助類 /// </su ...
  • 前面介紹了很多ABP系列的文章,一步一步的把我們日常開發中涉及到的Web API服務構建、登錄日誌和操作審計日誌、字典管理模塊、省份城市的信息維護、許可權管理模塊中的組織機構、用戶、角色、許可權、菜單等內容,以及配置管理模塊,界面的高級查詢處理等內容,同時我們把整個開發理念結合我們的代碼生成工具Data... ...
  • REST 全稱是 Representational State Transfer,有人說它是一種風格,並非一種標準,個人覺得挺有道理。它本身並沒有創造新的技術、組件與服務,更像是告訴大家如何更好地使用現有Web標準中的一些準則和約束,也不可否認,RESTFul 是目前最流行的 API 設計規範,用於 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...