Java旋转图像变成背景黑色的一部分

当我尝试旋转图像时,看起来背景的一部分变黑(我的图像是透明的)

背景白色
背景的一部分变黑

这是旋转图像的代码:

public BufferedImage rotate(int height, int width, BufferedImage originalImg, int angle) { BufferedImage rotateImage = null; try { rotateImage = new BufferedImage(height, width, BufferedImage.TYPE_INT_RGB); 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) { System.err.println(e); } return rotateImage; } 

所以,我下载了你的“原始”图像(不是正方形),修改它所以它是正方形,运行你的代码,得到一个java.awt.image.ImagingOpException: Unable to transform src imageexception,将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方法,因为它不需要widthheight值;

 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度的增量旋转图像