项目要求:生成电子证书
一、模板文件在OSS中,直接加载
二、向模板文件添加二维码
三、向模板文件添加多行文字
四、生成二维码,存入本地,
五、向模板文件添加二维码
代码实现步骤
一、建立.net 6 API项目,安装Nuget包
TestImageShapForNet6API
二、配置好OSS的相关功能,包括OSS绑定域名,配置SSL证书等,保证模板文件可以以URL的模式显示在浏览器中
http://oss.crabstech.com/code/21122504.jpg
获取OSS的AK信息和存储权限,以保证文件的正常读取和存入
三、创建内容行的model
using SixLabors.Fonts;
namespace TestImageShapForNet6API
{
public class DrawContent
{
public int x { get; set; }
public int y { get; set; }
public Font font { get; set; } = null!;
public string Text { get; set; } = null!;
public Color color { get; set; } = Color.Black;
}
}
四、创建OSS处理类(阿里云OSS ,具体文档请参考阿里云)
using Aliyun.OSS;
namespace TestImageShapForNet6API
{
public class OssHandle
{
const string Endpoint = "oss-cn-zhangjiakou.aliyuncs.com";
const string AccessKeyId = "你的keyId";
const string AccessKeySecret = "你的keysecret";
const string BucketName = "你的bucketname";
const string DirName = "自己起的目录名";
const string Url = "你自己的bucket绑定的域名";
public string PutImg2Oss(byte[] image,string objName)
{
var _img = new MemoryStream(image);
var client = new OssClient(Endpoint,AccessKeyId, AccessKeySecret);
try
{
var res = client.PutObject(BucketName, $"{DirName}/{objName}", _img);
Console.WriteLine(res.ToString);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return $"{Url}{DirName}/{objName}";
}
}
}
五、生成二维码
using ZXing.QrCode;
using ZXing;
namespace TestImageShapForNet6API
{
public class QrFile
{
public async Task<string> Output(string text)
{
var basePath = AppContext.BaseDirectory;
var filePath = Path.Combine(basePath, $"images/qr.jpg");
//生成二维码
var writer = new ZXing.ImageSharp.BarcodeWriter<Rgba32>
{
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions
{
Width = 400,
Height = 400,
Margin = 2,
}
};
var image = writer.WriteAsImageSharp<Rgba32>(text);
await image.SaveAsync(filePath);
Console.WriteLine("Image success");
return filePath;
}
}
}
六、创建合并方法,和调用方法。注意:“/”的问题,windows下对"/"和"\"容忍度比较高,怎么写基本都可以找到路径。但linux下一定要写 "/",否则会找不到文件
using SixLabors.Fonts;
using SixLabors.ImageSharp.Drawing.Processing;
using System.Net;
namespace TestImageShapForNet6API
{
public class MergeImg
{
/// <summary>
/// 图片上写字
/// https://docs.sixlabors.com/articles/imagesharp.drawing/gettingstarted.html#expanded-example
/// </summary>
/// <param name="ImagePath"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="txt"></param>
/// <param name="fontPath"></param>
/// <returns></returns>
private Image? drawingTextOnImage(string url, string qrImgPath, List<DrawContent> contList)
{
if (string.IsNullOrWhiteSpace(url) || contList is null || contList.Count < 1)
return null;
// 线上地址的图片,通过获取流的方式读取
WebRequest imgRequest = WebRequest.Create(url);
var res = (HttpWebResponse)imgRequest.GetResponse();
// 加载图片
var image = Image.Load(res.GetResponseStream());
// 按行向图片写入文字
foreach (var item in contList)
{
PointF point = new PointF(item.x, item.y);
image.Mutate(x => x.DrawText(item.Text, item.font, item.color, point));
}
// 加载二维码图片
var qrImg = Image.Load(qrImgPath);
// 向图片上添加二维码
image.Mutate(x => x.DrawImage(qrImg, new Point(1650, 3600), 1));
return image;
}
public async Task<string> DrawingTextOnImage()
{
var basePath = AppDomain.CurrentDomain.BaseDirectory;
var url = "http://oss.crabstech.com/code/21122504.jpg";
var qrImgPath = $"{basePath}images/qr.jpg";
var imgPath = $"{basePath}images/temp.jpg";
var contList = new List<DrawContent>();
var _first = new DrawContent
{
x = 600,
y = 1600,
Text = "张小斐",
font = SystemFonts.CreateFont("SimHei", 160, FontStyle.Regular),
color = Color.Green
};
contList.Add(_first);
var img = drawingTextOnImage(url, qrImgPath, contList);
var ms = new MemoryStream();
img.SaveAsJpeg(ms);
Console.WriteLine("生成成功");
var _imgMs = ms.ToArray();
var ossHandler = new OssHandle();
var result = await Task.Run(()=>{
return ossHandler.PutImg2Oss(_imgMs, "code-01.jpg");
});
return result;
}
}
}
七、创建controller ,调用方法实现
完整的program.cs
using TestImageShapForNet6API;
var builder = WebApplication.CreateBuilder(args);
var basePath = AppContext.BaseDirectory;
builder.Services.AddControllers();
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseStaticFiles();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
}
app.UseSwagger();
app.UseSwaggerUI();
app.MapGet("/qrcode", async () => {
var _qr = new QrFile();
return await _qr.Output("http://oss.crabstech.com/han/6d9a492bf72f4dc2bf59154c8c603c85_2.png");
})
.WithName("QrCode");
app.MapGet("/merimg", async () =>
{
var img = new MergeImg();
return await img.DrawingTextOnImage();
})
.WithName("MergeImg");
app.Run();
本地启动
先调用一次qrcode,再调用一次merimg。(只是为了测试两个API都可以单独使用,实际项目中请按照正常逻辑布署)
执行后我们得到了oss的Url地址:https://oss.crabstech.com/code/code-01.jpg
将地址粘贴到浏览器,得到已合成的图片文件
八、添加DockerFile
在项目中添加fonts文件夹,从c:\windows\fonts中拷贝基础的几个字体文件到项目的fonts中
在项目上点右键
此时生成Dockerfile文件
点击Dockerfile编辑
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
#设置时间为中国上海
ENV TZ=Asia/Shanghai
ENV DEBIAN_FRONTEND noninteractive
# 设置包源为阿里
RUN sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list \
&& apt-get clean
# 安装 tzdata 软件包
RUN apt-get update \
&& apt-get install -y tzdata \
&& ln -fs /usr/share/zoneinfo/$TZ /etc/localtime \
&& rm -rf /var/lib/apt/lists/ \
&& dpkg-reconfigure -f noninteractive tzdata
# 安装字体 注意:“/”的问题,windows下对"/"和"\"容忍度比较高,怎么写基本都可以找到路径。但linux下一定要写 "/",否则会找不到文件
COPY ["TestImageShapForNet6API/fonts/ARIAL.TTF","/usr/share/fonts/ttf-dejavu/ARIAL.TTF"]
COPY ["TestImageShapForNet6API/fonts/SIMFANG.TTF","/usr/share/fonts/ttf-dejavu/SIMFANG.TTF"]
COPY ["TestImageShapForNet6API/fonts/SIMHEI.TTF","/usr/share/fonts/ttf-dejavu/SIMHEI.TTF"]
COPY ["TestImageShapForNet6API/fonts/SIMKAI.TTF","/usr/share/fonts/ttf-dejavu/SIMKAI.TTF"]
COPY ["TestImageShapForNet6API/fonts/SIYUANSONGTI.TTF","/usr/share/fonts/ttf-dejavu/SIYUANSONGTI.TTF"]
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["TestImageShapForNet6API/TestImageShapForNet6API.csproj", "TestImageShapForNet6API/"]
RUN dotnet restore "TestImageShapForNet6API/TestImageShapForNet6API.csproj"
COPY . .
WORKDIR "/src/TestImageShapForNet6API"
RUN dotnet build "TestImageShapForNet6API.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "TestImageShapForNet6API.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "TestImageShapForNet6API.dll"]
再次点击右键,选择容器业务流程协调程序
点击编辑
version: '3.4'
services:
testimageshapfornet6api:
image: imagehandle:20231012.01
build:
context: "./TestImageShapForNet6API"
dockerfile: "./TestImageShapForNet6API/Dockerfile"
container_name: "imagehandle"
ports:
- 20205:80
- 20206:443
volumes:
- "./config/appsettings.json:/app/appsettings.json"
environment:
- ASPNETCORE_ENVIRONMENT=Production
restart: always
这里注意以下三点
至此在本地要准备的内容准备完毕
下面是在宝塔中操作的内容
一、在文件中找个地方创建个文件夹,一般放在以下这个地方
创建并打开文件夹,将项目文件压缩为zip后上传(压缩前记得编译生成一次),压缩时要选择最项目最外层文件夹,保证zip文件完整性
将文件上传到文件夹下,进行解压缩。
并且在该文件夹下建立config文件,将项目的appsetting.json拷贝到config下
将docker-compose.yml文件,拷贝到该目录下
解压拷贝完成后的目录状态如下
在该目录下的终端里,执行部署
docker-compose -f docker-compose.yml up
发布成功,是这样的
此时可以关闭这个终端,开一个新的终端查看
docker ps
或者在宝塔的Docker中查看
下面需要建立网站来映射docker
在宝塔中正常添加网站,绑定域名
然后修改配置文件
server
{
listen 80;
server_name 你的域名(确保已经解析到当前服务器了);
index index.html index.htm index.aspx ;
location / {
proxy_pass http://localhost:20205; #这里的端口号就是docker发布时,左侧的端口号
}
}
至此项目发布完毕
如果此时访问域名,显示404,不要慌,在域名后添加/swagger/index.html
即:http://你的域名/swagger/index.html
在oss中查看文件存储的时间,确定是刚刚生成无误
至此项目需求完成
项目下载地址
在.net 6下用SixLabors.ImageSharp实现图片跨平台处理https://gitee.com/shirleycat/image-sharp-for-net6-api