標籤:style blog color os io 檔案 for ar
C#在圖片上加文字,代碼如下:
1 /// <summary> 2 /// 圖片上方加文字,文字將會被180度反轉 3 /// </summary> 4 /// <param name="Img">待處理圖片</param> 5 /// <param name="WriteString">寫入的字串</param> 6 /// <param name="UpMargin">180度反轉後文字頂部距離上邊緣距離</param> 7 /// <param name="RightMargin">文字最左邊距離右邊緣距離</param> 8 /// <returns>Bitmap</returns> 9 public Bitmap WriteUp(Image Img, string WriteString, int UpMargin, int RightMargin)10 {11 return WriteUp(Img, WriteString, UpMargin, RightMargin, "宋體", 20);12 }13 14 /// <summary>15 /// 圖片上方加文字,文字將會被180度反轉16 /// </summary>17 /// <param name="Img">待處理圖片</param>18 /// <param name="WriteString">寫入的字串</param>19 /// <param name="UpMargin">180度反轉後文字頂部距離上邊緣距離</param>20 /// <param name="RightMargin">文字最左邊距離右邊緣距離</param>21 /// <param name="FontType">字型類型</param>22 /// <param name="FontSize">字型大小</param>23 /// <returns></returns>24 public Bitmap WriteUp(Image Img, string WriteString, int UpMargin, int RightMargin, string FontType, int FontSize)25 {26 //擷取圖片寬高27 int Width = Img.Width;28 int Height = Img.Height;29 //擷取圖片水平和垂直的解析度30 float dpiX = Img.HorizontalResolution;31 float dpiY = Img.VerticalResolution;32 //建立一個位元影像檔案33 Bitmap BitmapResult = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);34 //設定位元影像檔案的水平和垂直解析度 與Img一致35 BitmapResult.SetResolution(dpiX, dpiY);36 //在位元影像檔案上填充一個矩形框37 Graphics Grp = Graphics.FromImage(BitmapResult);38 System.Drawing.Rectangle Rec = new System.Drawing.Rectangle(0, 0, Width, Height);39 //向矩形框內填充Img40 Grp.DrawImage(Img, 0, 0, Rec, GraphicsUnit.Pixel);41 42 43 //平移Graphics對象44 Grp.TranslateTransform(Width - RightMargin, UpMargin);45 //設定Graphics對象的輸出角度以改變文字方向46 Grp.RotateTransform(180);47 //設定文字填充顏色48 Brush brush = Brushes.Black;49 //旋轉顯示文字50 Grp.DrawString(WriteString, new Font(FontType, FontSize, GraphicsUnit.Pixel), brush, 0, 0);51 //恢複全域變換矩陣52 Grp.ResetTransform();53 Grp.Dispose();54 GC.Collect();55 return BitmapResult;56 }