/// <summary> /// 创建图片字节数组 /// </summary> /// <returns></returns> private byte[] CreateImgData(string text) { byte[] resData = null; using (var img = new Bitmap(300, 300)) { using (var graphics = Graphics.FromImage(img)) { //消除锯齿 graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.TextRenderingHint = TextRenderingHint.AntiAlias; //字体设置(根据实际情况提供自定义字体的路径) var tffFilePath = Path.Combine(“方正彩云_GBK.ttf”); ; PrivateFontCollection pfc = new PrivateFontCollection(); pfc.AddFontFile(tffFilePath); var font = new Font(pfc.Families[0], 24, FontStyle.Regular); //文字信息 var size = graphics.MeasureString(text, font); var textPoint = new PointF((img.Width - size.Width) / 2, (img.Height - size.Height) / 2); //旋转 Matrix mtxSave = graphics.Transform; Matrix mtxRotate = graphics.Transform; mtxRotate.RotateAt(-45f, new PointF(img.Width / 2, img.Height / 2)); graphics.Transform = mtxRotate; //绘制文字 Brush b = new SolidBrush(Color.FromArgb(128, 204, 204, 204)); graphics.DrawString(text, font, b, (img.Width - size.Width) / 2, (img.Height - size.Height) / 2); //输出字节数组 using (var memoryStream = new MemoryStream()) { img.Save(memoryStream, ImageFormat.Png); resData = memoryStream.ToArray(); } } } return resData; }
时间: 2024-11-04 17:19:13