標籤:center 分享圖片 fromfile 對象 targe regular rpo ubi stat
最近有個需求是將產生的邀請碼與背景圖片合成成為新的圖片,尋找了一些資料後又整理了一遍,查到了一個群主的文章,雖然代碼略微有點問題,地址是: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; } }
C# 文字圖片產生與背景圖片合成