最近有个需求是将生成的邀请码与背景图片合成成为新的图片,查找了一些资料后又整理了一遍,查到了一个群主的帖子,虽然代码略微有点问题,地址是:https://www.cnblogs.com/stulzq/p/6137715.html,下面上修改后的代码,有两个资源图片,是自己做的,第一个是背景图片(500*600),第二个是前景图片(200*200)。
public ActionResult Index() { //生成邀请码图片 字符间距 带空格比较简单 //Image img = CreateImage("1 2 3 4 5 6", true, 12); //修改照片分辨率大小 //img = ResizeImage(img, 200, 100); //保存邀请码图片 //img.Save("D:/3.jpg"); //开始合并图片 Image ibpic = Image.FromFile("D:/1.jpg"); Image inpic = Image.FromFile("D:/2.jpg"); Bitmap bmp = CombinImage(ibpic, inpic, 0, -100); bmp.Save("D:/4.jpg", ImageFormat.Jpeg); return View(); }
/// <summary> /// 生成文字图片 /// </summary> /// <param name="text"></param> /// <param name="isBold"></param> /// <param name="fontSize"></param> public Image CreateImage(string text, bool isBold, int fontSize) { int wid = 400; int high = 200; Font font; if (isBold) { font = new Font("Arial", fontSize, FontStyle.Bold); } else { font = new Font("Arial", fontSize, FontStyle.Regular); } //绘笔颜色 SolidBrush brush = new SolidBrush(Color.Black); StringFormat format = new StringFormat(StringFormatFlags.NoClip); format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; Bitmap image = new Bitmap(wid, high); Graphics g = Graphics.FromImage(image); g.Clear(Color.White);//透明 RectangleF rect = new RectangleF(0, 0, wid, high); //绘制图片 g.DrawString(text, font, brush, rect, format); //释放对象 g.Dispose(); return image; } /// <summary> /// 合并图片 /// </summary> /// <param name="imgBack"></param> /// <param name="img"></param> /// <returns></returns> public static Bitmap CombinImage(Image imgBack, Image img, int xDeviation = 0, int yDeviation = 0) { Bitmap bmp = new Bitmap(imgBack.Width, imgBack.Height); Graphics g = Graphics.FromImage(bmp); g.Clear(Color.White); g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height); //白色边框 g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 + xDeviation - 1, imgBack.Height / 2 - img.Height / 2 + yDeviation - 1, img.Width + 2, img.Height + 2); //填充图片 g.DrawImage(img, imgBack.Width / 2 - img.Width / 2 + xDeviation, imgBack.Height / 2 - img.Height / 2 + yDeviation, img.Width, img.Height); GC.Collect(); return bmp; } /// <summary> /// Resize图片 /// </summary> /// <param name="bmp">原始Bitmap</param> /// <param name="newW">新的宽度</param> /// <param name="newH">新的高度</param> /// <returns>处理以后的图片</returns> public static Image ResizeImage(Image bmp, int newW, int newH) { try { Image b = new Bitmap(newW, newH); Graphics g = Graphics.FromImage(b); // 插值算法的质量 g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel); g.Dispose(); return b; } catch { return null; } }