bufferedImage Rotation Problem

Hi there,

I’m new to java 2D and have been having trouble rotating an image. The image i’m trying to rotate is stored as type .png, of type translucent as it has a transparent background. My problem is everytime i apply a rotation the image seems to get deformed resulting in a horrible swirly thing. Here’s the rotation methods i’ve been using.


   public BufferedImage getRotatedImage(double deg, GraphicsConfiguration gc, boolean antialias) {
        if (image == null) {
            System.out.println("rotateImage: input image is null");
            return null;
        }
        int w = image.getWidth();//null);
        int h = image.getHeight();//(null);
        int transparency = image.getColorModel().getTransparency();
        
        BufferedImage bi =  gc.createCompatibleImage(w, h, transparency);
       
        Graphics2D g2d = (Graphics2D)bi.getGraphics(); 
        g2d.setComposite(AlphaComposite.Src);

        
        if(antialias) {
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        }
        
        AffineTransform rotImg = new AffineTransform(); 
        rotImg.rotate(Math.toRadians(deg), ((double)w)/2, ((double)h)/2); //Get a transform to rotate the image
        g2d.transform(rotImg); 
        
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();
        return(bi);
    }
  
   public void rotateImage(GraphicsConfiguration gc) {
        int angle = 5;
       
        BufferedImage rotImage = getRotatedImage(angle, gc, false);
        image = rotImage;
        
   }

i tried adding this to the code

 AffineTransformOp op = new AffineTransformOp(rotImg, AffineTransformOp.TYPE_BILINEAR);
        image = op.filter(image, bi);

But that seems to replace the deformed swirls with a blurred image due to the interpolation.

I’d appreciate any advice.

Cheers,

Spav

I ran your code with a transparent background png image of my own but could not reproduce the
swirls. Maybe its not the code that is at fault here ?

The only thing I see that could corrupt the image is invoking the rotateImage method multiple
times in a row, as it overwrites the source image with the new rotated image which is then
used again as the source image for the next rotation. As an rotated image is never as good
as its original (pixels you know :slight_smile: if rotated long enough it will result in something pretty strange :slight_smile:

Good luck,

Erik

Thanks Erik,

You were right that was the problem.

Silly me…