1. 程式人生 > 其它 >C# 圖片處理

C# 圖片處理

按比例調整圖片尺寸

 1 #region 按比例調整圖片尺寸
 2 public static Bitmap GetThumbnail(Image bmp, int width, int height)
 3 {
 4     if (width == 0)
 5     {
 6         width = height * bmp.Width / bmp.Height;
 7     }
 8     if (height == 0)
 9     {
10         height = width * bmp.Height / bmp.Width;
11     }
12     Image imgSource = bmp;
13 Bitmap outBmp = new Bitmap(width, height); 14 Graphics g = Graphics.FromImage(outBmp); 15 g.Clear(Color.Transparent); 16 // 設定畫布的描繪質量 17 g.CompositingQuality = CompositingQuality.HighQuality; 18 g.SmoothingMode = SmoothingMode.HighQuality; 19 g.InterpolationMode = InterpolationMode.HighQualityBicubic;
20 21 g.DrawImage(imgSource, new Rectangle(0, 0, width, height + 1), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel); 22 23 g.Dispose(); 24 imgSource.Dispose(); 25 bmp.Dispose(); 26 return outBmp; 27 } 28 #endregion
按比例調整圖片尺寸

合成圖片

 1 /// <summary>
 2 /// 兩種圖片合併,類似相簿,有個背景圖,中間貼自己的目標圖片        
3 /// <param name="sourceImg">貼上的源圖片</param> 4 /// <param name="destImg">貼上的目標圖片</param> 5 /// <param name="name">合成圖片儲存路徑</param> 6 /// </summary> 7 public void CombinImage(string sourceImg, string destImg, string name) 8 { 9 System.Drawing.Image imgBack = System.Drawing.Image.FromFile(sourceImg); //相框圖片 10 System.Drawing.Image img = System.Drawing.Image.FromFile(destImg); //照片圖片 11 12 Bitmap bmp = new Bitmap(imgBack.Width, imgBack.Height); 13 14 Graphics g = Graphics.FromImage(bmp); 15 g.Clear(Color.White); 16 g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height); 17 //g.FillRectangle(System.Drawing.Brushes.Black, 16, 16, (int)112 + 2, ((int)73 + 2));//相片四周刷一層黑色邊框 18 19 //g.DrawImage(img, 照片與相框的左邊距, 照片與相框的上邊距, 照片寬, 照片高); 20 g.DrawImage(img, imgBack.Width / 2 - img.Width / 2 + 0, imgBack.Height / 2 - img.Height / 2 + 0, img.Width, img.Height); 21 GC.Collect(); 22 23 //儲存指定格式圖片 24 bmp.Save(name, ImageFormat.Png); 25 }
合成圖片