python裁剪不规则区域_c#教程之c#图片处理之图片裁剪成不规则图形

本文介绍了如何使用C#进行图片裁剪,特别是裁剪成不规则图形。通过示例代码展示了如何创建GraphicsPath对象定义裁剪路径,以及使用BitmapCrop方法实现裁剪操作。裁剪过程包括判断像素点是否在路径内,并将符合条件的像素复制到新图片上,同时将原图相应区域设为透明。
摘要由CSDN通过智能技术生成

https://www.xin3721.com/eschool/

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

好了,那就开始贴代码了

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

复制代码 代码如下:

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");

}

}

以下为裁剪的关键代码

复制代码 代码如下:

///

/// 图片截图

///

/// 原图

/// 裁剪路径

/// 输出图

///

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;

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值