.net图片裁剪抠图之性能优化

//.net图片裁剪抠图:
1.将不坐标点存入GraphicsPath中;
GraphicsPath gPath = new GraphicsPath();
2.
通常我们判断一个坐标点是否在闭合区间内通采用GraphicsPath.IsVisible(),但事实证明这种方法判断效率及其低,这里我们采用Region.IsVisible(),
经测试,GraphicsPath.IsVisible()处理一张800*800的图片需要14s以上时间。Region.IsVisible()只需要1s.

  //

        /// <summary>

        /// 图片截图

        /// </summary>

        /// <param name="bitmap">原图路径</param>

        /// <param name="path">裁剪路径</param>

        /// <returns></returns>

        public static Bitmap BitmapCropGzf(Bitmap bitmap, GraphicsPath path)

        {

            RectangleF rect = path.GetBounds();

            int left = (int)rect.Left;

            int top = (int)rect.Top;

            int width = (int)rect.Width;

            int height = (int)rect.Height;

            //先进行剪裁:

            Bitmap imgCropped = new Bitmap(width, height);

            Graphics objGraphics = Graphics.FromImage(imgCropped);

            objGraphics.Clear(System.Drawing.Color.White);

            int intStartTop = -top;

            int intStartLeft = -left;

            Bitmap b = new Bitmap(bitmap);

            objGraphics.DrawImage(b, intStartLeft, intStartTop);

            b.Dispose();

            objGraphics.Dispose();

            Region r = new Region(path);

            GC.Collect(0);

            for (int i = left; i < left + width; i++)

            {

                for (int j = top; j < top + height; j++)

                {

                    //判断坐标是否在路径中   

                    if (!r.IsVisible(i, j))

                    {

                        imgCropped.SetPixel(i - left, j - top, System.Drawing.Color.Transparent);

                    }

                }

            }

            return imgCropped;

        }

  

你可能感兴趣的:(.net)