2014-03-28 72 views
2

我寫了下面的代碼合併2個圖像。我的需求很簡單,圖像總是相同的大小,所以不需要定位。我可以稍後處理...我想知道的是,我可以修改它以將文本標籤合併爲imgFront到圖像imgBack上。結果返回的結果將是一個新的圖像,我的文字在上面。C# - 合併文本和圖像

這可能嗎?怎麼樣?

public static byte[] ImageMerge(Image imgBack, Image imgFront, Int32 width = 200, Int32 height = 200) 
{ 
    using (imgBack) 
    { 
     using (var bitmap = new Bitmap(width, height)) 
     { 
      using (var canvas = Graphics.FromImage(bitmap)) 
      { 
       canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; 
       canvas.DrawImage(imgBack, new Rectangle(0, 0, width, height), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel); 
       canvas.DrawImage(imgFront, new Rectangle(0, 0, width, height), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel); 
       canvas.Save(); 
      } 
      try 
      { 
       return ImageToByte(bitmap); 
      } 
      catch (Exception ex) 
      { 
       return null; 
      } 
     } 
    } 
} 
+2

是的,當然你可以使用DrawString()繪製文本,什麼不起作用? (但也許我不明白你的問題) –

+1

謝謝阿德里亞諾!這正是我所期待的! (我發誓我通過智能感知列表看了看,沒有看到....) –

回答

1

下面是已完成的代碼。我無法相信我不會早早分享!

public static byte[] ImageTextMerge(Image imgBack, string str, Int32 x, Int32 y, Int32 w, Int32 h, Int32 width = 200, Int32 height = 200) 
{ 
    using (imgBack) 
    { 
     using (var bitmap = new Bitmap(width, height)) 
     { 
      using (var canvas = Graphics.FromImage(bitmap)) 
      { 
       canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; 
       canvas.DrawImage(imgBack, new Rectangle(0, 0, width, height), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel); 

       // Create font and brush 
       Font drawFont = new Font("Arial", 20); 
       SolidBrush drawBrush = new SolidBrush(Color.Black); 

       // Create rectangle for drawing. 
       RectangleF drawRect = new RectangleF(x, y, w, h); 

       // Draw rectangle to screen. 
       Pen blackPen = new Pen(Color.Transparent); 
       canvas.DrawRectangle(blackPen, x, y, w, h); 

       // Set format of string. 
       StringFormat drawFormat = new StringFormat(); 
       drawFormat.Alignment = StringAlignment.Near; 

       // Draw string to screen. 
       canvas.DrawString(str, drawFont, drawBrush, drawRect, drawFormat); 
       canvas.Save(); 
      } 
      try 
      { 
       return ImageToByte(bitmap); 
      } 
      catch (Exception ex) 
      { 
       return null; 
      } 
     } 
    } 
}