我尝试使用 setRGB
和 BufferedImage
在 Java 中旋转图像,但我得到了一个奇怪的结果。有人知道为什么吗?
BufferedImage pic1 = ImageIO.read(new File("Images/Input-1.bmp"));
int width = pic1.getWidth(null);
int height = pic1.getHeight(null);
double angle = Math.toRadians(90);
double sin = Math.sin(angle);
double cos = Math.cos(angle);
double x0 = 0.5 * (width - 1); // point to rotate about
double y0 = 0.5 * (height - 1); // center of image
BufferedImage pic2 = pic1;
// rotation
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
double a = x - x0;
double b = y - y0;
int xx = (int) (+a * cos - b * sin + x0);
int yy = (int) (+a * sin + b * cos + y0);
if (xx >= 0 && xx < width && yy >= 0 && yy < height) {
pic2.setRGB(x, y, pic1.getRGB(xx, yy));
}
}
}
ImageIO.write(pic2, "bmp", new File("Images/Output2.bmp"));
LEFT 侧是原始图片,RIGHT 侧是我的结果。有谁知道我该如何解决?
感谢您的帮助。
最佳答案
问题是您使用的是相同的图像作为输入和输出:
缓冲图片 pic2 = pic1;
您必须为 pic2 创建另一个图像,然后进行旋转,将像素从 Image1 复制到 Image2。
但是请注意,使用 getRGB 和 setRGB 速度非常慢。如果直接操作像素,速度会提高 100 倍。
关于java - BufferedImage setRGB 奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505824/