2

I am trying to rotate an instance of a BufferImage named pic when I try this it resizes and skews and crops the image, any advice to get it to work properly

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

When I have it rotate 90˚ it works fine so I'm wondering if the problem is that it is the shape of the image?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Aaron
  • 171
  • 10

1 Answers1

5

For use with AffineTransform, you can square an image using something like this:

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;
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • I'm actually trying to use a rectangular image that is 2x as wide as it is long, any advice? – Aaron May 17 '12 at 23:43
  • The method above was used in the same context, `AffineTransformOp`. Does it solve the problem? If not, please edit your question to include an [sscce](http://sscce.org/) that exhibits the problem you describe. This [example](http://stackoverflow.com/a/10610126/230513) illustrates using a widely available image. – trashgod May 17 '12 at 23:54