C# 圖片的裁剪,兩個圖片合成一個圖片
阿新 • • 發佈:2019-02-12
/// <summary> /// 圖片裁剪,生成新圖,儲存在同一目錄下,名字加_new,格式1.png 新圖1_new.png /// </summary> /// <param name="picPath">要修改圖片完整路徑</param> /// <param name="x">修改起點x座標</param> /// <param name="y">修改起點y座標</param> /// <param name="width">新圖寬度</param> /// <param name="height">新圖高度</param> public static void caijianpic(String picPath,int x,int y,int width,int height) { //圖片路徑 String oldPath = picPath; //新圖片路徑 String newPath = System.IO.Path.GetExtension(oldPath); //計算新的檔名,在舊檔名後加_new newPath = oldPath.Substring(0, oldPath.Length - newPath.Length) + "_new" + newPath; //定義擷取矩形 System.Drawing.Rectangle cropArea = new System.Drawing.Rectangle(x, y, width, height); //要擷取的區域大小 //載入圖片 System.Drawing.Image img = System.Drawing.Image.FromStream(new System.IO.MemoryStream(System.IO.File.ReadAllBytes(oldPath))); //判斷超出的位置否 if ((img.Width < x + width) || img.Height < y + height) { MessageBox.Show("裁剪尺寸超出原有尺寸!"); img.Dispose(); return; } //定義Bitmap物件 System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(img); //進行裁剪 System.Drawing.Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat); //儲存成新檔案 bmpCrop.Save(newPath); //釋放物件 img.Dispose(); bmpCrop.Dispose(); } /// <summary> /// 呼叫此函式後使此兩種圖片合併,類似相簿,有個 /// 背景圖,中間貼自己的目標圖片 /// </summary> /// <param name="sourceImg">貼上的源圖片</param> /// <param name="destImg">貼上的目標圖片</param> public static Image CombinImage(string sourceImg, string destImg) { Image imgBack = System.Drawing.Image.FromFile(sourceImg); //相框圖片 Image img = System.Drawing.Image.FromFile(destImg); //照片圖片 //從指定的System.Drawing.Image建立新的System.Drawing.Graphics Graphics g = Graphics.FromImage(imgBack); //g.DrawImage(imgBack, 0, 0, 148, 124); // g.DrawImage(imgBack, 0, 0, 相框寬, 相框高); g.FillRectangle(System.Drawing.Brushes.Black, -50, -50, (int)212, ((int)203));//相片四周刷一層黑色邊框,這裡沒有,需要調尺寸 //g.DrawImage(img, 照片與相框的左邊距, 照片與相框的上邊距, 照片寬, 照片高); g.DrawImage(img, -50, -50, 212, 203); GC.Collect(); string saveImagePath ="D:/測試資料夾/sss.png"; //save new image to file system. imgBack.Save(saveImagePath, ImageFormat.Png); return imgBack; }