1. 程式人生 > >C#圖片處理之:圖片縮放和剪裁

C#圖片處理之:圖片縮放和剪裁

應聽眾點播要求,今天說說用C#做圖片的縮放和剪裁,相信很多人會對這部分內容感興趣,畢竟這個操作太實用了。

其實在GDI+中,縮放和剪裁可以看作同一個操作,無非就是原始區域的選擇不同罷了。空口無憑,先看具體演算法可能更好理解。

        /// <summary>
        /// Resize圖片
        /// </summary>
        /// <param name="bmp">原始Bitmap</param>
        /// <param name="newW">新的寬度</param>
        /// <param name="newH">新的高度</param>
        /// <param name="Mode">保留著,暫時未用</param>
        /// <returns>處理以後的圖片</returns>
        public static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH, int Mode)
        {
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);

                // 插值演算法的質量
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();

                return b;
            }
            catch
            {
                return null;
            }
        }

// ===============================

         /// <summary>
        /// 剪裁 -- 用GDI+
        /// </summary>
        /// <param name="b">原始Bitmap</param>
        /// <param name="StartX">開始座標X</param>
        /// <param name="StartY">開始座標Y</param>
        /// <param name="iWidth">寬度</param>
        /// <param name="iHeight">高度</param>
        /// <returns>剪裁後的Bitmap</returns>
        public static Bitmap KiCut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight)
        {
            if (b == null)
            {
                return null;
            }

            int w = b.Width;
            int h = b.Height;

            if (StartX >= w || StartY >= h)
            {
                return null;
            }

            if (StartX + iWidth > w)
            {
                iWidth = w - StartX;
            }

            if (StartY + iHeight > h)
            {
                iHeight = h - StartY;
            }

            try
            {
                Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);

                Graphics g = Graphics.FromImage(bmpOut);
                g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
                g.Dispose();

                return bmpOut;
            }
            catch
            {
                return null;
            }
        }

注意到區別了嗎?提示,g.DrawImage中第二個new Rectangle。

目標其實都是new Rectangle(0, 0, iWidth, iHeight),縮放演算法把整個原始圖都往目標區域裡塞new Rectangle(0, 0, bmp.Width, bmp.Height),而剪裁只是把原始區域上等寬等高的那個區域new Rectangle(StartX, StartY, iWidth, iHeight)1:1的塞到目標區域裡。很容易吧。