.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,將其放入項目的根目錄內方便調用。
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的源碼中,發(fā)現有畫圓形的工具類可以使用,在這里直接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圖片生成內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!