因此,我下载了“原始”图像(不是正方形),对其进行了修改,使其变为正方形,运行您的代码,得到了java.awt.image.ImagingOpException:无法转换src图像异常,将BufferedImage.TYPE_INT_RGB更改为BufferedImage .TYPE_INT_ARGB并得到…
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
try {
BufferedImage img = ImageIO.read(Main.class.getResource("/Block.jpg"));
BufferedImage rotate = rotate(img.getHeight(), img.getWidth(), img, 90);
JPanel panel = new JPanel();
panel.add(new JLabel(new ImageIcon(img)));
panel.add(new JLabel(new ImageIcon(rotate)));
JOptionPane.showMessageDialog(null, panel);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static BufferedImage rotate(int height, int width, BufferedImage originalImg, int angle) {
BufferedImage rotateImage = null;
try {
rotateImage = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB);
AffineTransform a90 = AffineTransform.getRotateInstance(Math.toRadians(angle), height / 2, width / 2);
AffineTransformOp op90 = new AffineTransformOp(a90, AffineTransformOp.TYPE_BILINEAR);
op90.filter(originalImg, rotateImage);
} catch (Exception e) {
e.printStackTrace();
}
return rotateImage;
}
}
我的“直觉”感觉是还要修改rotate方法,因为它不需要宽度和高度值.
public static BufferedImage rotate(BufferedImage originalImg, int angle) {
BufferedImage rotateImage = null;
try {
rotateImage = new BufferedImage(originalImg.getWidth(), originalImg.getHeight(), BufferedImage.TYPE_INT_ARGB);
AffineTransform a90 = AffineTransform.getRotateInstance(Math.toRadians(angle), originalImg.getWidth() / 2, originalImg.getHeight() / 2);
AffineTransformOp op90 = new AffineTransformOp(a90, AffineTransformOp.TYPE_BILINEAR);
op90.filter(originalImg, rotateImage);
} catch (Exception e) {
e.printStackTrace();
}
return rotateImage;
}
它应该直接使用原始图像的尺寸.这将突出显示图像中可能存在的错误.这还假设您只想将图像旋转90度