/// <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; }
新聞熱點
疑難解答