欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#图片处理之图片裁剪成不规则图形

程序员文章站 2024-02-22 13:12:34
为了让大家知道下面内容是否是自己想要的,我先发效果图。 好了,那就开始贴代码了 以下为一个按钮的事件,为裁剪准备图片、裁剪路径、保存路径 复制代码 代码如下:priv...

为了让大家知道下面内容是否是自己想要的,我先发效果图。

c#图片处理之图片裁剪成不规则图形

好了,那就开始贴代码了

以下为一个按钮的事件,为裁剪准备图片、裁剪路径、保存路径

复制代码 代码如下:

private void button1_click(object sender, eventargs e)
        {
            graphicspath path = new graphicspath();
            point[] p = {
                            new point(424,244),
                            new point(240,440),
                            new point(340,552),
                            new point(550,526),
                            new point(478,366),
                            new point(348,660),
                            new point(424,244)
                        };
            path.addlines(p);
            openfiledialog openfiledialog = new openfiledialog();

            openfiledialog.filter = @"bitmap文件(*.bmp)|*.bmp|jpeg文件(*.jpg)|*.jpg|所有合适文件(*.bmp,*.jpg)|*.bmp;*.jpg";

            openfiledialog.filterindex = 3;

            openfiledialog.restoredirectory = true;

            if (dialogresult.ok == openfiledialog.showdialog())
            {

                bitmap bit = (bitmap)bitmap.fromfile(openfiledialog.filename, false);

                bitmap newbit = null;
                bitmapcrop(bit, path, out newbit);
                newbit.save(@"c:\users\public\pictures\sample pictures\沙漠22.jpg");
            }
        }

以下为裁剪的关键代码

复制代码 代码如下:

/// <summary>
        /// 图片截图
        /// </summary>
        /// <param name="bitmap">原图</param>
        /// <param name="path">裁剪路径</param>
        /// <param name="outputbitmap">输出图</param>
        /// <returns></returns>
        public static bitmap bitmapcrop(bitmap bitmap, graphicspath path, out bitmap outputbitmap)
        {
            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 image = (bitmap)bitmap.clone();
            outputbitmap = new bitmap(width, height);
            for (int i = left; i < left + width; i++)
            {
                for (int j = top; j < top + height; j++)
                {
                    //判断坐标是否在路径中  
                    if (path.isvisible(i, j))
                    {
                        //复制原图区域的像素到输出图片  
                        outputbitmap.setpixel(i - left, j - top, image.getpixel(i, j));
                        //设置原图这部分区域为透明  
                        image.setpixel(i, j, color.fromargb(0, image.getpixel(i, j)));
                    }
                    else
                    {
                        outputbitmap.setpixel(i - left, j - top, color.fromargb(0, 255, 255, 255));
                    }
                }
            }
            bitmap.dispose();
            return image;
        }

有了这个前台只需要获取用户的鼠标路径传到后台就可以。