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

时间:2015-12-07 20:59:54

标签: java swing image-rotation affinetransform rgba

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

Background white
Part of background turns black

以下是旋转图像的代码:

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;
}

1 个答案:

答案 0 :(得分:4)

所以,我下载了你的“原始”图片(不是正方形),修改它以使其成为正方形,运行代码,得到java.awt.image.ImagingOpException: Unable to transform src image例外,将BufferedImage.TYPE_INT_RGB更改为{{1}并得到......

Rotated

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; } } 方法,因为它不需要rotatewidth值;

height

它应该直接使用原始图像的尺寸。这将突出显示图像中可能出现的错误。这也假设您只想以90度的增量旋转图像