Search code examples
javagraphics2d

Java image rotation with AffineTransform outputs black image, but works well when resized


I am just trying to rotate a JPG file by 90 degrees. However my code outputs image (BufferedImage) that is completely black.

Here's the way to reproduce: (Download 3.jpg here)

private static BufferedImage transform(BufferedImage originalImage) {
    BufferedImage newImage = null;
    AffineTransform tx = new AffineTransform();
    tx.rotate(Math.PI / 2, originalImage.getWidth() / 2, originalImage.getHeight() / 2);

    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC);
    newImage = op.filter(originalImage, newImage);

    return newImage;
}

public static void main(String[] args) throws Exception {
    BufferedImage bi = transform(ImageIO.read(new File(
            "3.jpg")));
    ImageIO.write(bi, "jpg", new File("out.jpg"));

}

What's wrong here?

(if I give this black output BufferedImage to a image resizer library, it gets resized well, original image is still there.)


Solution

  • Passing a new BufferedImage into the filter() method rather than letting it create its own works (not completely black).

    Also the transform did not appear to work correctly, the image ended up being offset in the destination. I was able to fix it by manually applying the necessary translations, note these work in reverse order, and in the destination image the width = the old height, and height = the old width.

    AffineTransform tx = new AffineTransform();
    
    // last, width = height and height = width :)
    tx.translate(originalImage.getHeight() / 2,originalImage.getWidth() / 2);
    tx.rotate(Math.PI / 2);
    // first - center image at the origin so rotate works OK
    tx.translate(-originalImage.getWidth() / 2,-originalImage.getHeight() / 2);
    
    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
    
    // new destination image where height = width and width = height.
    BufferedImage newImage =new BufferedImage(originalImage.getHeight(), originalImage.getWidth(), originalImage.getType());
    op.filter(originalImage, newImage);
    

    The javadoc for filter() states that it will create a BufferedImage for you, I'm still unsure why this does not work, there must be an issue here.

     If the destination image is null, a BufferedImage is created with the source ColorModel.