.net core Graphics合成图片加文字
引用:
using System;
using System.Drawing;
using System.Drawing.Text;
代码
static void Main(string[] args)
{
var result = AddText("主图路径","上层图片路径","文本1","文本2","文本3");
result.Save(@"保存路径");
result.Dispose();
}
public static Bitmap AddText(string zimgPath, string fimgPath,string text1, string text2, string text3)
{
Image zimg = Image.FromFile(zimgPath);
Image fimg = CirclePhoto(Image.FromFile(fimgPath), 132);
//设置主图宽高
int width = 444;
int heigth = 382;
Bitmap bmp = new Bitmap(width, heigth);
Graphics graph = Graphics.FromImage(bmp);
var fs = new PrivateFontCollection();
fs.AddFontFile(@"D:\PingFang Bold.ttf");//获取文件字体
//实例化字体
FontFamily fontFamily = fs.Families[0];
Font font1 = new Font(fontFamily, 40, GraphicsUnit.Pixel);
Font font2 = new Font(fontFamily, 26, GraphicsUnit.Pixel);
//设置图片文字剧中begin
SizeF sf1 = graph.MeasureString(text1, font1);
SizeF sf2 = graph.MeasureString(text2, font2);
SizeF sf3 = graph.MeasureString(text3, font2);
float x = (width - fimg.Width) / 2;
float x1 = (width - sf1.Width)/ 2;
float x2 = (width - sf2.Width) / 2;
float x3 = (width - sf3.Width) / 2;
float y = 20;
float y1 = 20+fimg.Height+10;
float y2 = y1+sf1.Height+10;
float y3 = y2 + sf2.Height + 10;
//end
graph.DrawImage(zimg, 0, 0, width, heigth);
graph.DrawImage(fimg, x, y, 132, 132);
graph.DrawString(text1, font1, new SolidBrush(Color.White), x1, y1);
graph.DrawString(text2, font2, new SolidBrush(Color.White), x2, y2);
graph.DrawString(text3, font2, new SolidBrush(Color.White), x3, y3);
graph.Dispose();
zimg.Dispose();
return bmp;
}
/// <summary>
/// 圆形图处理
/// </summary>
/// <param name="file">需要进行操作的图片</param>
/// <param name="size">裁剪成格式(正方形size)</param>
/// <returns></returns>
public static Bitmap CirclePhoto(Image file, int size)
{
using (Image i = file)
{
Bitmap b = new Bitmap(size, size);
using (Graphics g = Graphics.FromImage(b))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.DrawImage(i, 0, 0, b.Width, b.Height);
int r = Math.Min(b.Width, b.Height) / 2;
PointF c = new PointF(b.Width / 2.0F, b.Height / 2.0F);
for (int h = 0; h < b.Height; h++)
for (int w = 0; w < b.Width; w++)
if ((int)Math.Pow(r, 2) < ((int)Math.Pow(w * 1.0 - c.X, 2) + (int)Math.Pow(h * 1.0 - c.Y, 2)))
{
b.SetPixel(w, h, Color.Transparent);
}
//画背景色圆
using (Pen p = new Pen(System.Drawing.SystemColors.Control))
g.DrawEllipse(p, 0, 0, b.Width, b.Height);
}
return b;
}
}