.NetCore使用ImageSharp進行圖片的生成
ImageSharp是對NetCore平臺擴展的一個圖像處理方案,以往網(wǎng)上的案例多以生成文字及畫出簡單圖形、驗證碼等方式進行探討和實踐。
今天我分享一下所在公司項目的實際應(yīng)用案例,導(dǎo)出微信二維碼圖片,圓形頭像等等。
一、源碼獲取
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
二、應(yīng)用
1.在圖片中畫出文字
首先要注意字體問題,Windows自帶的字體一般存儲于 C:\Windows\Fonts文件夾內(nèi),如果是部署在Linux系統(tǒng)的應(yīng)用程序,則存儲于usr/share/fonts 文件夾內(nèi)。以黑體為例,我們找到對應(yīng)的字體文件 SIMHEI.TTF,將其放入項目的根目錄內(nèi)方便調(diào)用。
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 ( "陸家嘴旗艦店", //文字內(nèi)容 font, Rgba32.Black, //文字顏色 new PointF(100,100)) //坐標位置(浮點) ); image.Save(path); }
關(guān)于Image.Load()獲取圖片方法的使用,可以直接讀取Stream類型的流,也可以根據(jù)圖片的本地路徑獲取。
//線上地址的圖片,通過獲取流的方式讀取 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的源碼中,發(fā)現(xiàn)有畫圓形的工具類可以使用,在這里直接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); } } }
有了畫圓形的方法,我們只需要調(diào)用ConvertToAvatar() 方法把方形的圖片轉(zhuǎn)為圓形,畫在圖片上即可。
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類型轉(zhuǎn)換為流的格式從而可以通過Image.Load()方法獲取圖片信息成為了關(guān)鍵。在這里我還是引用到了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); } } } }
這樣數(shù)據(jù)就存入了stream中,但直接用ImageSharp去Load處理過的流可能會有些問題,為了保險,我將數(shù)據(jù)流中的byte取出,實例化了一個新的MemoryStream類型。這樣,就可以獲取到二維碼的圖片了。
//Matrix為BitMatrix類型數(shù)據(jù),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));
最后附上保存后圖片的效果:
本篇內(nèi)容到此就結(jié)束了,非常感謝您的觀看,有機會的話,希望能夠一起討論技術(shù),一起成長!
到此這篇關(guān)于.NetCore如何使用ImageSharp進行圖片的生成的文章就介紹到這了,更多相關(guān).NetCore使用ImageSharp圖片生成內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ASP.NET Core使用JWT認證授權(quán)的方法
這篇文章主要介紹了ASP.NET Core使用JWT認證授權(quán)的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11VB.NET設(shè)置屏幕分辨率、顏色位數(shù)、刷新率 實例代碼
這篇文章介紹了VB.NET設(shè)置屏幕分辨率、顏色位數(shù)、刷新率 實例代碼,有需要的朋友可以參考一下2013-07-07在Framework4.0中實現(xiàn)延遲加載的實現(xiàn)方法
延遲加載,亦稱延遲實例化,延遲初始化等,主要表達的思想是,把對象的創(chuàng)建將會延遲到使用時創(chuàng)建,而不是在對象實例化時創(chuàng)建對象,即用時才加載。2011-08-08