用Java写一个实现旋转模糊滤镜的程序
时间: 2023-09-03 13:16:33 浏览: 42
以下是一个用Java实现旋转模糊滤镜的程序示例:
```
import java.awt.image.BufferedImage;
import java.awt.Color;
import java.io.File;
import javax.imageio.ImageIO;
public class RotateBlurFilter {
public static void main(String[] args) throws Exception {
// 读取原始图片
BufferedImage originalImage = ImageIO.read(new File("input.jpg"));
int width = originalImage.getWidth();
int height = originalImage.getHeight();
// 创建新的图片,准备绘制旋转模糊滤镜后的图像
BufferedImage rotatedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 转换角度,这里以45度为例
double angle = Math.toRadians(45);
// 定义模糊半径
int radius = 10;
// 定义旋转中心点
int centerX = width / 2;
int centerY = height / 2;
// 逐个像素计算旋转后的位置,然后计算周围像素的平均值,作为新的像素值
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
// 计算旋转后的坐标
int newX = (int) ((x - centerX) * Math.cos(angle) - (y - centerY) * Math.sin(angle)) + centerX;
int newY = (int) ((x - centerX) * Math.sin(angle) + (y - centerY) * Math.cos(angle)) + centerY;
// 计算周围像素的平均值
int sumRed = 0;
int sumGreen = 0;
int sumBlue = 0;
int count = 0;
for (int i = -radius; i <= radius; i++) {
for (int j = -radius; j <= radius; j++) {
int neighborX = newX + i;
int neighborY = newY + j;
if (neighborX >= 0 && neighborX < width && neighborY >= 0 && neighborY < height) {
Color neighborColor = new Color(originalImage.getRGB(neighborX, neighborY));
sumRed += neighborColor.getRed();
sumGreen += neighborColor.getGreen();
sumBlue += neighborColor.getBlue();
count++;
}
}
}
int avgRed = (int) (sumRed / count);
int avgGreen = (int) (sumGreen / count);
int avgBlue = (int) (sumBlue / count);
// 设置新的像素值
Color newColor = new Color(avgRed, avgGreen, avgBlue);
rotatedImage.setRGB(x, y, newColor.getRGB());
}
}
// 将旋转模糊后的图片输出到文件
ImageIO.write(rotatedImage, "jpg", new File("output.jpg"));
}
}
```
以上程序通过逐个像素计算旋转后的位置,然后计算周围像素的平均值,作为新的像素值,最终输出旋转模糊后的图片。其中,角度、模糊半径、旋转中心点等参数可以根据实际需求进行调整。