111 lines
3.3 KiB
C#
111 lines
3.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Drawing.Drawing2D;
|
|
using System.Drawing;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Windows.Media;
|
|
using System.Drawing.Imaging;
|
|
using System.IO;
|
|
|
|
namespace Demo.Common.Helpers
|
|
{
|
|
public class AvatatHelper
|
|
{
|
|
private static Image cameraCloseImage = null;
|
|
public static Image CameraCloseImage
|
|
{
|
|
get
|
|
{
|
|
if (cameraCloseImage != null)
|
|
{
|
|
return cameraCloseImage;
|
|
}
|
|
using (var fileStream = new FileStream($@"Assets/camera_close.png", FileMode.Open, FileAccess.Read))
|
|
{
|
|
using var _imageStream = new MemoryStream();
|
|
fileStream.CopyTo(_imageStream);
|
|
cameraCloseImage = Image.FromStream(_imageStream);
|
|
}
|
|
|
|
return cameraCloseImage;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
/// 获取姓名对应的圆形图片
|
|
/// </summary>
|
|
/// <param name="name"></param>
|
|
/// <param name="width"></param>
|
|
/// <param name="height"></param>
|
|
/// <returns></returns>
|
|
public static Bitmap GetNickNameImage(string name, int width = 132, int height = 132)
|
|
{
|
|
string color = "#2B6EC0";
|
|
if (string.IsNullOrEmpty(name))
|
|
{
|
|
return null;
|
|
}
|
|
string firstName = GetFirstTwoChars(name);
|
|
Bitmap img = new Bitmap(width, height);
|
|
Graphics g = Graphics.FromImage(img);
|
|
|
|
// 启用抗锯齿
|
|
g.SmoothingMode = SmoothingMode.AntiAlias;
|
|
|
|
// 创建圆形路径
|
|
GraphicsPath path = new GraphicsPath();
|
|
path.AddEllipse(0, 0, width, height);
|
|
|
|
// 设置裁剪区域为圆形
|
|
g.SetClip(path);
|
|
|
|
// 填充背景色
|
|
System.Drawing.Brush brush = new SolidBrush(ColorTranslator.FromHtml(color));
|
|
g.FillEllipse(brush, 0, 0, width, height);
|
|
|
|
// 填充文字
|
|
Font font = new Font("微软雅黑", 50);
|
|
SizeF firstSize = g.MeasureString(firstName, font);
|
|
g.DrawString(firstName, font, System.Drawing.Brushes.White,
|
|
new PointF((img.Width - firstSize.Width) / 2, (img.Height - firstSize.Height) / 2));
|
|
|
|
g.Dispose();
|
|
path.Dispose();
|
|
brush.Dispose();
|
|
font.Dispose();
|
|
|
|
return img;
|
|
}
|
|
|
|
|
|
public static string GetFirstTwoChars(string input)
|
|
{
|
|
if (string.IsNullOrEmpty(input))
|
|
return string.Empty;
|
|
input = input.Trim();
|
|
return input[..Math.Min(2, input.Length)];
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 保存图片到磁盘
|
|
/// </summary>
|
|
/// <param name="name"></param>
|
|
/// <param name="targetFile"></param>
|
|
/// <param name="width"></param>
|
|
/// <param name="height"></param>
|
|
/// <returns></returns>
|
|
public static Bitmap SaveNameImage(string name, string targetFile, int width = 132, int height = 132)
|
|
{
|
|
Bitmap img = GetNickNameImage(name, width, height);
|
|
img.Save(targetFile + ".png", ImageFormat.Png);
|
|
img.Dispose();
|
|
return img;
|
|
}
|
|
}
|
|
}
|