如何用Java做到图片的图像模糊效果

Given an image, either in 24-bit color or in 24-bit grayscale format, implement an image blur effect by randomly moving pixels off from their original positions as a method with the header below:

public static BufferedImage blur(BufferedImage src, int offset)

where src is the object reference of an input image and offset is the amount of circular random movement off the original pixel position. The return value of this method is an object reference of the resulting image.

This image blur effect can be visualized above. Image (1) is the original image. Image (2) is the result after applying the effect with offset 10. Image (3) is the result obtained with offset 20. Image (4) is the result obtained with offset 30.

The idea of the algorithm to achieve this effect is given below:

For each pixel (xnew, ynew) in the resulting image, let
• offsetX = random integer (in range between 0 and offset, inclusive) – offset /2
• offsetY = random integer (in range between 0 and offset, inclusive) – offset / 2
• x = xnew + offsetX
• y = ynew + offsetY

ResultImg(xnew,ynew) = OriginalImg(x, y)

That is to assign the color value of pixel (xnew,ynew) in the new image to that of the pixel (x,y) in the original image.

该回答引用ChatGPT

以下是实现模糊效果的Java代码:

import java.awt.image.BufferedImage;
import java.util.Random;

public class ImageBlur {

    public static BufferedImage blur(BufferedImage src, int offset) {
        int width = src.getWidth();
        int height = src.getHeight();
        BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Random random = new Random();

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int offsetX = random.nextInt(offset + 1) - offset / 2;
                int offsetY = random.nextInt(offset + 1) - offset / 2;
                int newX = x + offsetX;
                int newY = y + offsetY;

                if (newX < 0) {
                    newX = 0;
                } else if (newX >= width) {
                    newX = width - 1;
                }

                if (newY < 0) {
                    newY = 0;
                } else if (newY >= height) {
                    newY = height - 1;
                }

                int rgb = src.getRGB(newX, newY);
                dest.setRGB(x, y, rgb);
            }
        }

        return dest;
    }

}

这段代码首先创建了一个与原始图像相同大小的新图像对象。然后,使用Java中的随机数生成器类Random,为每个像素计算偏移量,然后将其应用于新图像中的每个像素。最后,将新图像返回给调用者。请注意,为了确保我们不会超出原始图像的边界,需要进行边缘检查。


这个算法只是一种简单的方法来实现模糊效果,结果可能并不是很理想。还有很多其他更复杂的算法可以实现更好的模糊效果。