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

后端 未结 2 616
执念已碎
执念已碎 2020-12-10 08:24

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 reproduc

相关标签:
2条回答
  • 2020-12-10 08:48

    If you were open to the idea of using a 3rd party lib (very small, just 2 classes) imgscalr can do this for you in a single line while working around all the filter gotchas that different image types can cause.

    Using Scalr.rotate(...) would look something like this:

    BufferedImage newImage = Scalr.rotate(originalImage, Rotation.CW_90);
    

    If this rotation is part of a larger app that processes images, you can even do this asynchronously if you needed that (AsyncScalr class).

    imgscalr is under an Apache 2 license and all source is available; if you'd rather do this yourself by-hand, read through the code for the rotate() method, I've documented all the gotchas that can spring up when working with filters in Java2D.

    Hope that helps!

    0 讨论(0)
  • 2020-12-10 08:59

    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.
    
    0 讨论(0)
提交回复
热议问题