c# 矩形截取图片

发布时间 2023-03-22 21:13:21作者: 小小橘子
 1 ///   <summary>   
 2         ///   从图片中截取部分生成新图   
 3         ///   </summary>   
 4         ///   <param   name="sFromFilePath">原始图片</param>   
 5         ///   <param   name="saveFilePath">生成新图</param>   
 6         ///   <param   name="width">截取图片宽度</param>   
 7         ///   <param   name="height">截取图片高度</param>   
 8         ///   <param   name="spaceX">截图图片X坐标</param>   
 9         ///   <param   name="spaceY">截取图片Y坐标</param>   
10         public static void CaptureImage(string sFromFilePath, string saveFilePath, int width, int height, int spaceX, int spaceY)
11         {
12             //载入底图   
13             Image fromImage = Image.FromFile(sFromFilePath);
14             int x = 0;   //截取X坐标   
15             int y = 0;   //截取Y坐标   
16                          //原图宽与生成图片宽   之差       
17                          //当小于0(即原图宽小于要生成的图)时,新图宽度为较小者   即原图宽度   X坐标则为0     
18                          //当大于0(即原图宽大于要生成的图)时,新图宽度为设置值   即width         X坐标则为   sX与spaceX之间较小者   
19                          //Y方向同理   
20             int sX = fromImage.Width - width;
21             int sY = fromImage.Height - height;
22             if (sX > 0)
23             {
24                 x = sX > spaceX ? spaceX : sX;
25             }
26             else
27             {
28                 width = fromImage.Width;
29             }
30             if (sY > 0)
31             {
32                 y = sY > spaceY ? spaceY : sY;
33             }
34             else
35             {
36                 height = fromImage.Height;
37             }
38 
39             //创建新图位图   
40             Bitmap bitmap = new Bitmap(width, height);
41             //创建作图区域   
42             Graphics graphic = Graphics.FromImage(bitmap);
43             //截取原图相应区域写入作图区   
44             graphic.DrawImage(fromImage, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
45             //从作图区生成新图   
46             Image saveImage = Image.FromHbitmap(bitmap.GetHbitmap());
47             //保存图象   
48             if (!Directory.Exists(Path.GetDirectoryName(saveFilePath)))
49             {
50                 Directory.CreateDirectory(Path.GetDirectoryName(saveFilePath));
51             }
52 
53             saveImage.Save(saveFilePath, System.Drawing.Imaging.ImageFormat.Png);//此處出現錯誤,可能圖片(saveFilePath)正在被其他應用訪問
54             //释放资源   
55             saveImage.Dispose();
56         }