.NetCore使用ImageSharp進(jìn)行圖片的生成
ImageSharp是對(duì)NetCore平臺(tái)擴(kuò)展的一個(gè)圖像處理方案,以往網(wǎng)上的案例多以生成文字及畫(huà)出簡(jiǎn)單圖形、驗(yàn)證碼等方式進(jìn)行探討和實(shí)踐。
今天我分享一下所在公司項(xiàng)目的實(shí)際應(yīng)用案例,導(dǎo)出微信二維碼圖片,圓形頭像等等。
一、源碼獲取
Git項(xiàng)目地址:https://github.com/SixLabors/ImageSharp
安裝這兩個(gè)包即可:
Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0001
Install-Package SixLabors.ImageSharp.Drawing -Version 1.0.0-beta0001
二、應(yīng)用
1.在圖片中畫(huà)出文字
首先要注意字體問(wèn)題,Windows自帶的字體一般存儲(chǔ)于 C:\Windows\Fonts文件夾內(nèi),如果是部署在Linux系統(tǒng)的應(yīng)用程序,則存儲(chǔ)于usr/share/fonts 文件夾內(nèi)。以黑體為例,我們找到對(duì)應(yīng)的字體文件 SIMHEI.TTF,將其放入項(xiàng)目的根目錄內(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)) //坐標(biāo)位置(浮點(diǎn)) ); image.Save(path); }
關(guān)于Image.Load()獲取圖片方法的使用,可以直接讀取Stream類型的流,也可以根據(jù)圖片的本地路徑獲取。
//線上地址的圖片,通過(guò)獲取流的方式讀取 WebRequest imgRequest = WebRequest.Create(url); var res = (HttpWebResponse)imgRequest.GetResponse(); var image = Image.Load(res.GetResponseStream());
獲取文字的像素寬度,可以使用:
var str = "我是什么長(zhǎng)度"; var size = TextMeasurer.Measure(str, new RendererOptions(new Font(fontfamily,50))); var width = size.Width;
2.在圖片中畫(huà)出圓形的頭像
我在ImageSharp的源碼中,發(fā)現(xiàn)有畫(huà)圓形的工具類可以使用,在這里直接copy出來(lái)。
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); } } }
有了畫(huà)圓形的方法,我們只需要調(diào)用ConvertToAvatar() 方法把方形的圖片轉(zhuǎn)為圓形,畫(huà)在圖片上即可。
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類型
我以微信獲取的二維碼類型為例,因?yàn)槲业捻?xiàng)目中二維碼是從微信公眾號(hào)平臺(tái)API獲取,在這次獲取圖片中,將BitMatrix類型轉(zhuǎn)換為流的格式從而可以通過(guò)Image.Load()方法獲取圖片信息成為了關(guān)鍵。在這里我還是引用到了System.Drawing,可以單獨(dú)提取公用方法。
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處理過(guò)的流可能會(huì)有些問(wèn)題,為了保險(xiǎn),我將數(shù)據(jù)流中的byte取出,實(shí)例化了一個(gè)新的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é)束了,非常感謝您的觀看,有機(jī)會(huì)的話,希望能夠一起討論技術(shù),一起成長(zhǎng)!
到此這篇關(guān)于.NetCore如何使用ImageSharp進(jìn)行圖片的生成的文章就介紹到這了,更多相關(guān).NetCore使用ImageSharp圖片生成內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ASP.NET Core使用JWT認(rèn)證授權(quán)的方法
這篇文章主要介紹了ASP.NET Core使用JWT認(rèn)證授權(quán)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11asp.net兩級(jí)聯(lián)動(dòng)(包含添加和修改)
兩級(jí)聯(lián)動(dòng)實(shí)現(xiàn)代碼2009-01-01VB.NET設(shè)置屏幕分辨率、顏色位數(shù)、刷新率 實(shí)例代碼
這篇文章介紹了VB.NET設(shè)置屏幕分辨率、顏色位數(shù)、刷新率 實(shí)例代碼,有需要的朋友可以參考一下2013-07-07asp.net 操作cookie的簡(jiǎn)單實(shí)例
這篇文章主要介紹了asp.net 操作cookie的簡(jiǎn)單實(shí)例,有需要的朋友可以參考一下2013-12-12ASP.NET顯示農(nóng)歷時(shí)間改進(jìn)版
這篇文章主要介紹了ASP.NET顯示農(nóng)歷時(shí)間改進(jìn)版,是針對(duì)前面一篇ASP.NET顯示農(nóng)歷時(shí)間的改進(jìn)版,實(shí)現(xiàn)了比較簡(jiǎn)單的封裝,增加了易用性,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2014-11-11Asp.Net實(shí)現(xiàn)的通用分頁(yè)函數(shù)
這篇文章主要介紹了Asp.Net實(shí)現(xiàn)的通用分頁(yè)函數(shù),結(jié)合實(shí)例形勢(shì)分析了asp.net分頁(yè)函數(shù)的功能,定義及使用技巧,需要的朋友可以參考下2016-04-04在Framework4.0中實(shí)現(xiàn)延遲加載的實(shí)現(xiàn)方法
延遲加載,亦稱延遲實(shí)例化,延遲初始化等,主要表達(dá)的思想是,把對(duì)象的創(chuàng)建將會(huì)延遲到使用時(shí)創(chuàng)建,而不是在對(duì)象實(shí)例化時(shí)創(chuàng)建對(duì)象,即用時(shí)才加載。2011-08-08