C# Blurring an Image

╄→гoц情女王★ 提交于 2019-12-25 10:02:32

问题


I am trying to blur an image in C# by going through all of the pixels of one image and then creating a new Bitmap with the color of the pixels in the original image divided by the pixel count to create an average color. When I run it, nothing happens. Here's the code:

private void blurToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Bitmap img = new Bitmap(pictureBox1.Image);
        Bitmap blurPic = new Bitmap(img.Width, img.Height);

        Int32 avgR = 0, avgG = 0, avgB = 0;
        Int32 blurPixelCount = 0;

        for (int y = 0; y < img.Height; y++)
        {
            for (int x = 0; x < img.Width; x++)
            {
                Color pixel = img.GetPixel(x, y);
                avgR += pixel.R;
                avgG += pixel.G;
                avgB += pixel.B;

                blurPixelCount++;
            }
        }

        avgR = avgR / blurPixelCount;
        avgG = avgG / blurPixelCount;
        avgB = avgB / blurPixelCount;

        for (int y = 0; y < img.Height; y++)
        {
            for (int x = 0; x < img.Width; x++)
            {
                blurPic.SetPixel(x, y, Color.FromArgb(avgR, avgG, avgB));
            }
        }

        img = blurPic;
    }

Thanks!


回答1:


Use pictureBox1.Image = blurPic; at the end of your method.




回答2:


This is the easiest way to blur images in c# code but N.B you have to wait for an image to load completely so that you can start working on it

In short, we are going to use the ImageOpened event handler for your image. So we are going to use the WriteableBitmap class which has methods for blurring images and applying all sorts of effect to an image.

WriteableBitExtensions contain the GaussianBlur5x5 which is what we are going to use.

This code assumes that you are getting the image from a url, so we first download the image to get the contents of the stream from the web. But if your image is local, then you can first convert it to a IRandomAccessStream and pass it as an argument.

double height = pictureBox1.ActualHeight;
        double width = pictureBox1.ActualWidth;

        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync("image-url-goes-here");

        var webResponse = response.Content.ReadAsStreamAsync();
        randomStream = webResponse.Result.AsRandomAccessStream();
        randomStream.Seek(0);


        wb = wb.Crop(50, 50, 400, 400);
        wb = wb.Resize(10,10 ,         WriteableBitmapExtensions.Interpolation.NearestNeighbor);
        wb = WriteableBitmapExtensions.Convolute(wb,WriteableBitmapExtensions.KernelGaussianBlur5x5);

        pictureBox1.Source= wb;


来源:https://stackoverflow.com/questions/19010914/c-sharp-blurring-an-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!