Java旋转ImageBuffer失败

时间:2012-05-17 22:13:54

标签: java swing bufferedimage graphics2d

我正在尝试旋转一个名为pic的BufferImage的实例,当我尝试它调整大小和倾斜并裁剪图像时,任何建议让它正常工作

public void rotate(double rads){
    AffineTransform tx = new AffineTransform();
    tx.rotate(rads,pic.getWidth()/2,pic.getHeight()/2);
    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
    pic = op.filter(pic, null);
}

当我旋转90˚它工作正常所以我想知道问题是它是图像的形状吗?

1 个答案:

答案 0 :(得分:5)

要与AffineTransform一起使用,您可以使用以下内容对图像进行平方:

private BufferedImage getImage(String name) {
    BufferedImage image;
    try {
        image = ImageIO.read(new File(name));
    } catch (IOException ioe) {
        return errorImage;
    }
    int w = image.getWidth();
    int h = image.getHeight();
    int max = Math.max(w, h);
    max = (int) Math.sqrt(2 * max * max);
    BufferedImage square = new BufferedImage(
            max, max, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = square.createGraphics();
    g2d.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.drawImage(image, (max - w) / 2, (max - h) / 2, null);
    g2d.dispose();
    return square;
}