.NetCore使用ImageSharp進(jìn)行圖片的生成
ImageSharp是對(duì)NetCore平臺(tái)擴(kuò)展的一個(gè)圖像處理方案,以往網(wǎng)上的案例多以生成文字及畫出簡(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.在圖片中畫出文字
首先要注意字體問(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.在圖片中畫出圓形的頭像
我在ImageSharp的源碼中,發(fā)現(xiàn)有畫圓形的工具類可以使用,在這里直接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);
}
}
}有了畫圓形的方法,我們只需要調(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類型
我以微信獲取的二維碼類型為例,因?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 數(shù)據(jù)綁定的實(shí)例代碼
這篇文章介紹了asp.net 數(shù)據(jù)綁定的實(shí)例代碼,有需要的朋友可以參考一下2013-07-07
ASP.NET中MVC從后臺(tái)控制器傳遞數(shù)據(jù)到前臺(tái)視圖的方式
這篇文章主要介紹了ASP.NET中MVC從后臺(tái)控制器傳遞數(shù)據(jù)到前臺(tái)視圖的方式,以實(shí)例形式較為詳細(xì)的分析了asp.net中MVC數(shù)據(jù)傳遞的具體實(shí)現(xiàn)方法,需要的朋友可以參考下2014-12-12
asp.net Http異常eurl.axd出錯(cuò)信息解決方法
在IIS6中同時(shí)啟用了ASP.NET 2.0 和 ASP.NET 4.0 后,網(wǎng)站程序可能會(huì)出現(xiàn)如下錯(cuò)誤:“ System.Web.HttpException: Path ‘//eurl.axd/‘ was not found. ”2011-08-08
xUnit 編寫 ASP.NET Core 單元測(cè)試的方法
這篇文章主要介紹了xUnit 編寫 ASP.NET Core 單元測(cè)試的方法,文中代碼非常詳細(xì),幫助大家更好的參考和學(xué)習(xí),感興趣的朋友可以了解下2020-06-06
ASP.NET Core使用JWT自定義角色并實(shí)現(xiàn)策略授權(quán)需要的接口
這篇文章介紹了ASP.NET Core使用JWT自定義角色并實(shí)現(xiàn)策略授權(quán)需要的接口,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-01-01
獲取遠(yuǎn)程網(wǎng)頁(yè)的內(nèi)容之一(downmoon原創(chuàng))
獲取遠(yuǎn)程網(wǎng)頁(yè)的內(nèi)容之一(downmoon原創(chuàng))...2007-03-03

