首頁 > 軟體

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

2022-06-17 10:00:10

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:WindowsFonts資料夾內,如果是部署在Linux系統的應用程式,則儲存於usr/share/fonts 資料夾內。以黑體為例,我們找到對應的字型檔案 SIMHEI.TTF,將其放入專案的根目錄內方便呼叫。

   var path = "Image/Mud.png"                                  //圖片路徑
   FontCollection fonts = new FontCollection();
    FontFamily fontfamily = fonts.Install("Source/SIMHEI.TTF"); //字型的路徑     var font  = new Font(fontfamily,50);
    using (Image<Rgba32> image = Image.Load(path))
    {
        image.Mutate(x => x.         DrawText (
                  "陸家嘴旗艦店",           //文字內容
                  font,
                 Rgba32.Black,           //文字顏色
                 new PointF(100,100))    //座標位置(浮點)
          );
      image.Save(path);
    }

關於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出來。

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.Primitives;
using SixLabors.Shapes;
using System;
using System.Collections.Generic;
using System.Text;
namespace CodePicDownload
{
    public static class CupCircularHelper
    {
        public static IImageProcessingContext<Rgba32> ConvertToAvatar(this IImageProcessingContext<Rgba32> processingContext, Size size, float cornerRadius)
        {
            return processingContext.Resize(new ResizeOptions
            {
                Size = size,
                Mode = ResizeMode.Crop
            }).Apply(i => ApplyRoundedCorners(i, cornerRadius));
        }
        // This method can be seen as an inline implementation of an `IImageProcessor`:
        // (The combination of `IImageOperations.Apply()` + this could be replaced with an `IImageProcessor`)
        private static void ApplyRoundedCorners(Image<Rgba32> img, float cornerRadius)
        {
            IPathCollection corners = BuildCorners(img.Width, img.Height, cornerRadius);
            var graphicOptions = new GraphicsOptions(true)
            {
                AlphaCompositionMode = PixelAlphaCompositionMode.DestOut // enforces that any part of this shape that has color is punched out of the background
            };
            // mutating in here as we already have a cloned original
            // use any color (not Transparent), so the corners will be clipped
            img.Mutate(x => x.Fill(graphicOptions, Rgba32.LimeGreen, corners));
        }
        private static IPathCollection BuildCorners(int imageWidth, int imageHeight, float cornerRadius)
        {
            // first create a square
            var rect = new RectangularPolygon(-0.5f, -0.5f, cornerRadius, cornerRadius);
            // then cut out of the square a circle so we are left with a corner
            IPath cornerTopLeft = rect.Clip(new EllipsePolygon(cornerRadius - 0.5f, cornerRadius - 0.5f, cornerRadius));
            // corner is now a corner shape positions top left
            //lets make 3 more positioned correctly, we can do that by translating the orgional artound the center of the image
            float rightPos = imageWidth - cornerTopLeft.Bounds.Width + 1;
            float bottomPos = imageHeight - cornerTopLeft.Bounds.Height + 1;
            // move it across the width of the image - the width of the shape
            IPath cornerTopRight = cornerTopLeft.RotateDegree(90).Translate(rightPos, 0);
            IPath cornerBottomLeft = cornerTopLeft.RotateDegree(-90).Translate(0, bottomPos);
            IPath cornerBottomRight = cornerTopLeft.RotateDegree(180).Translate(rightPos, bottomPos);
            return new PathCollection(cornerTopLeft, cornerBottomLeft, cornerTopRight, cornerBottomRight);
        }
  }
}

有了畫圓形的方法,我們只需要呼叫ConvertToAvatar() 方法把方形的圖片轉為圓形,畫在圖片上即可。

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

3.處理二維條碼的BitMatrix型別

我以微信獲取的二維條碼型別為例,因為我的專案中二維條碼是從微信公眾號平臺API獲取,在這次獲取圖片中,將BitMatrix型別轉換為流的格式從而可以通過Image.Load()方法獲取圖片資訊成為了關鍵。在這裡我還是參照到了System.Drawing,可以單獨提取公用方法。

public void WriteToStream(BitMatrix QrMatrix, ImageFormat imageFormat, Stream stream)
        {
            if (imageFormat != ImageFormat.Exif && imageFormat != ImageFormat.Icon && imageFormat != ImageFormat.MemoryBmp)
            {
                DrawingSize size = m_iSize.GetSize(QrMatrix?.Width ?? 21);
                using (Bitmap bitmap = new Bitmap(size.CodeWidth, size.CodeWidth))
                {
                    using (Graphics graphics = Graphics.FromImage(bitmap))
                    {
                        Draw(graphics, QrMatrix);
                        bitmap.Save(stream, imageFormat);
                    }
                }
            }
        }

這樣資料就存入了stream中,但直接用ImageSharp去Load處理過的流可能會有些問題,為了保險,我將資料流中的byte取出,範例化了一個新的MemoryStream型別。這樣,就可以獲取到二維條碼的圖片了。

//Matrix為BitMatrix型別資料,ImageFormat我選擇了png型別
MemoryStream ms = new MemoryStream();
WriteToStream(Matrix,System.Drawing.Imaging.ImageFormat.Png, ms);
byte[] data = new byte[ms.Length];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(data, 0, Convert.ToInt32(ms.Length));
var image =  Image.Load(new MemoryStream(data));

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

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

到此這篇關於.NetCore如何使用ImageSharp進行圖片的生成的文章就介紹到這了,更多相關.NetCore使用ImageSharp圖片生成內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com