C# picturebox内图片柔化
时间: 2023-09-26 21:07:41 浏览: 90
要在C#的PictureBox内对图片进行柔化处理,你可以使用System.Drawing命名空间中的相关类和方法。下面是一个简单的示例代码,演示如何实现图片柔化效果:
```csharp
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace ImageProcessing
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Image Files (*.jpg, *.png, *.bmp)|*.jpg;*.png;*.bmp";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
pictureBox.Image = new Bitmap(openFileDialog.FileName);
}
}
private void btnBlur_Click(object sender, EventArgs e)
{
if (pictureBox.Image != null)
{
Bitmap originalImage = new Bitmap(pictureBox.Image);
Bitmap blurredImage = ApplyGaussianBlur(originalImage, 5); // 使用高斯模糊半径为5
pictureBox.Image = blurredImage;
}
}
private Bitmap ApplyGaussianBlur(Bitmap image, int blurRadius)
{
Bitmap blurredImage = new Bitmap(image.Width, image.Height);
using (Graphics graphics = Graphics.FromImage(blurredImage))
{
Rectangle rectangle = new Rectangle(0, 0, image.Width, image.Height);
graphics.DrawImage(image, rectangle, rectangle, GraphicsUnit.Pixel);
for (int i = 0; i < blurRadius; i++)
{
using (Bitmap tempImage = new Bitmap(blurredImage))
{
using (Graphics tempGraphics = Graphics.FromImage(blurredImage))
{
tempGraphics.DrawImage(tempImage, rectangle, rectangle, GraphicsUnit.Pixel);
}
using (ImageAttributes attributes = new ImageAttributes())
{
attributes.SetColorMatrix(new ColorMatrix { Matrix33 = 1f / blurRadius }); // 调整颜色矩阵以实现模糊效果
graphics.DrawImage(blurredImage, rectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
}
}
}
}
return blurredImage;
}
}
}
```
上述代码中的`ApplyGaussianBlur`方法使用了高斯模糊算法来对图像进行柔化处理。你可以根据需要调整模糊半径以获得不同程度的柔化效果。代码中还包括了打开图片和应用柔化效果的按钮点击事件处理。你可以根据实际情况进行修改和扩展。
希望对你有所帮助!如果有任何问题,请随时提问。
阅读全文
相关推荐


















