简体   繁体   中英

C# Blurring an Image

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!

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

This is the easiest way to blur images in c# code but NB 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM