天天看點

C#圖檔裁切,生成新圖檔

/// 圖檔裁剪,生成新圖,儲存在同一目錄下,名字加_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 cutPicture(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();
        }