简单使用 .Net 基本库。您可以根据自己的要求进行更改。 基本目的是为了创建用户个人资料头像图像,如果用户没有使用特定图像作为个人资料,则将使用默认图像。 我们需要制作两种常见类型的图片:矩形和圆形。
对于圆形图像
public MemoryStream GenerateCircle(string firstName, string lastName)
{
var avatarString = string.Format("{0}{1}", firstName[0], lastName[0]).ToUpper();
var randomIndex = new Random().Next(0, _BackgroundColours.Count - 1);
var bgColour = _BackgroundColours[randomIndex];
var bmp = new Bitmap(192, 192);
var sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
var font = new Font("Arial", 72, FontStyle.Bold, GraphicsUnit.Pixel);
var graphics = Graphics.FromImage(bmp);
graphics.Clear(Color.Transparent);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
using (Brush b = new SolidBrush(ColorTranslator.FromHtml("#" + bgColour)))
{
graphics.FillEllipse(b, new Rectangle(0, 0, 192, 192));
}
graphics.DrawString(avatarString, font, new SolidBrush(Color.WhiteSmoke), 95, 100, sf);
graphics.Flush();
var ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Png);
return ms;
}
对于矩形图片:
public MemoryStream GenerateRactangle(string firstName, string lastName)
{
var avatarString = string.Format("{0}{1}", firstName[0], lastName[0]).ToUpper();
var randomIndex = new Random().Next(0, _BackgroundColours.Count - 1);
var bgColour = _BackgroundColours[randomIndex];
var bmp = new Bitmap(192, 192);
var sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
var font = new Font("Arial", 72, FontStyle.Bold, GraphicsUnit.Pixel);
var graphics = Graphics.FromImage(bmp);
graphics.Clear((Color)new ColorConverter().ConvertFromString("#" + bgColour));
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
graphics.DrawString(avatarString, font, new SolidBrush(Color.WhiteSmoke), new RectangleF(0, 0, 192, 192), sf);
graphics.Flush();
var ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Png);
return ms;
}
用于生成背景随机颜色的方法:
private List<string> _BackgroundColours = new List<string> { "339966", "3366CC", "CC33FF", "FF5050" };
我希望这可以帮到你,如果有任何建议请提出来以便改进。
你可以为每个字母保存一张图片
/your_path/a.png
/your_path/b.bng,
/your_path/c.png
...
在加载用户配置文件时,如果数据库中没有用户的图片文件名,则使用其初始字母代替加载图像的文件名。
例如...
SELECT name, address,
COALESCE(picture, CONCAT("/your_path/", LEFT(name, 1),".png")) as picture
FROM users_table WHERE... ;