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(,)) //坐标位置(浮点)
);
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,)));
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 + ;
float bottomPos = imageHeight - cornerTopLeft.Bounds.Height + ; // move it across the width of the image - the width of the shape
IPath cornerTopRight = cornerTopLeft.RotateDegree().Translate(rightPos, );
IPath cornerBottomLeft = cornerTopLeft.RotateDegree(-).Translate(, bottomPos);
IPath cornerBottomRight = cornerTopLeft.RotateDegree().Translate(rightPos, bottomPos); return new PathCollection(cornerTopLeft, cornerBottomLeft, cornerTopRight, cornerBottomRight);
}
}
}

有了画圆形的方法,我们只需要调用ConvertToAvatar() 方法把方形的图片转为圆形,画在图片上即可。

 using (Image<Rgba32> image = Image.Load("Image/Mud.png"))
{
var logoWidth = ;
var logo = Image.Load("Image/Logo.png")
logo.Mutate(x => x.ConvertToAvatar(new Size(logoWidth, logoWidth), logoWidth / ));
image.Mutate(x => x.DrawImage(logo, new Point(, ), ));
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 ?? );
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(, SeekOrigin.Begin);
ms.Read(data, , Convert.ToInt32(ms.Length));
var image = Image.Load(new MemoryStream(data));

最后附上保存后图片的效果:

本篇内容到此就结束了,非常感谢您的观看,有机会的话,希望能够一起讨论技术,一起成长!

.NetCore如何使用ImageSharp进行图片的生成的更多相关文章

  1. 基于.NetCore开发博客项目 StarBlog - (15) 生成随机尺寸图片

    系列文章 基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客? 基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目 基于.NetC ...

  2. Atitit 图片 验证码生成attilax总结

    Atitit 图片 验证码生成attilax总结 1.1. 图片验证码总结1 1.2. 镂空文字  打散 干扰线 文字扭曲 粘连2 1.1. 图片验证码总结 因此,CAPTCHA在图片验证码这一应用点 ...

  3. WindowsPhone8中实现圆形图片的生成显示

    原文 WindowsPhone8中实现圆形图片的生成显示 很多软件中(比如QQ)用到了许多圆形图片,作为用户头像等等,原始图片往往是方形的,那么怎么样将方形的图片显示成圆形呢? 一种方法是当背景为固定 ...

  4. C#放缩、截取、合并图片并生成高质量新图的类

    原文:C#放缩.截取.合并图片并生成高质量新图的类 using System;using System.Drawing;using System.Drawing.Imaging;using Syste ...

  5. 开发工具类API调用的代码示例合集:六位图片验证码生成、四位图片验证码生成、简单验证码识别等

    以下示例代码适用于 www.apishop.net 网站下的API,使用本文提及的接口调用代码示例前,您需要先申请相应的API服务. 六位图片验证码生成:包括纯数字.小写字母.大写字母.大小写混合.数 ...

  6. 深度学习之 GAN 进行 mnist 图片的生成

    深度学习之 GAN 进行 mnist 图片的生成 mport numpy as np import os import codecs import torch from PIL import Imag ...

  7. php背景图片上生成二维码,二维码上带logo 代码示例 (原)

    依赖库文件 phpqrcode.php (下载地址://www.jb51.net/codes/189897.html :或者在官网下载:http://phpqrcode.sourceforge.net ...

  8. java图片操作--生成与原图对称的图片

    java图片操作--生成与原图对称的图片 package com.pay.common.util; import java.awt.image.BufferedImage; import java.i ...

  9. Flask实战第40天:图片验证码生成技术

    图片验证码生成 安装pillow pip install pillow 在utils下新建python package命名为captcha 把需要需要用到的字体放在captcha下 编辑captcha ...

随机推荐

  1. python 设计模式之模板方法模式

    1.模板方法模式定义 模板模式定义如下:定义一个操作中的算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定的步骤.子类实现的具体方法叫作基本方法,实现对 ...

  2. gitment初始化评论跳回博客首页

    表现 众所周知,gitment评论系统需要初始化以创建对应的issue,可是我在点击login with github的时候,总是跳向博客首页!WTF!什么鬼?这样不程序啊? 排查 1.F12查看lo ...

  3. bootargs中的rootwait 与rootdelay有什么区别?

    答: rootwait是无限期等待,而rootdelay可以指定等待的时间,更加灵活.

  4. JV默认是如何处理异常

    main函数收到这个问题时,有两种处理方式: a:自己将该问题处理,然后继续运行 b:自己没有针对的处理方式,只有交给调用main的jvm来处理 jvm有一个默认的异常处理机制,就将该异常进行处理. ...

  5. 002-01-RestTemplate-配置使用说明

    一.概述 Spring RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写 ...

  6. osgViewer:: Viewer::advance() osg多线程与智能指针

    void ViewerBase::frame(double simulationTime) { if (_done) return; // OSG_NOTICE<<std::endl< ...

  7. 23 Flutter官方推荐的状态管理库provider的使用

    加群452892873 下载对应21可文件,运行方法,建好项目,直接替换lib目录,在往pubspec.yaml添加上一下扩展. cupertino_icons: ^ flutter_swiper: ...

  8. React Native 中的 Flex Box 的用法(水平布局、垂直布局、水平居中、垂直居中、居中布局)

     版权声明:本文仅供个人学习. CSS 中 Flex-Box 语法链接 http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html Flex 是 ...

  9. 使用MockMvc进行springboot调试(SpringbootTest)

    测试前关闭web项目.springboot启动程序WebApplication.class 笔者本地自定了端口SpringBootTest.WebEnvironment.DEFINED_PORT 代码 ...

  10. (错误)在VMmare中安装centos后不能联网

    一.问题 在VMmare中安装centos后不能联网 在Xshell无法连接centos 二.解决方法 2.1 点击Network Adapter 设置如下图所示,首先我们在虚拟机中将网络配置设置成N ...