I'm trying to rotate an image clockwise and counter clockwise. With the help of this answer from Sri Harsha Chilakapati I managed to get it working according to my needs. This is the code
String rotateURL = tmp_dir + "/" + strusername + "rotate.jpg";
File fileJPG = new File(tmp_dir + "/" + strusername + "FullSize.jpg");
fullImage = ImageIO.read(fileJPG);
leftImage = rotateLeft(fullImage, 90);
writeImageToFile(leftImage, "jpg", new File(rotateURL));
public static BufferedImage rotateLeft(BufferedImage img, double angle)
{
double sin = Math.abs(Math.sin(Math.toRadians(angle))),
cos = Math.abs(Math.cos(Math.toRadians(angle)));
int w = img.getWidth(null), h = img.getHeight(null);
int neww = (int) Math.floor(w*cos + h*sin),
newh = (int) Math.floor(h*cos + w*sin);
BufferedImage bimg = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bimg.createGraphics();
g.translate((neww-w)/2, (newh-h)/2);
g.rotate(Math.toRadians(angle), w/2, h/2);
g.drawRenderedImage(img, null);
g.dispose();
return bimg;
}
However, I seem to have a caching (not sure about this) problem where I need to put a Thread.sleep(9000);
above the fullImage = ImageIO.read(fileJPG);
line otherwise my image element would contain the right dimension but doesn't show it rotated. Since a picture says more than a 1000 words:
To be clear, this is how it should look like:
Now the sleep is a solution but to be honest I don't want to wait 9 seconds (counted it, 8 doesn't work) before it rotates. Also, I'm not sure what it gives on a slower computer because it could be possible that it will take longer?
Since AffineTransform quadrantrotate
should be more efficient (and the question is marked as duplicate) I tried following answer but the problem still occurs. The code:
AffineTransform at = new AffineTransform();
at.translate(100, 40);
at.quadrantRotate(1, img.getWidth() / 2, img.getHeight() / 2);
g.drawImage(img, at, null);
g.dispose();
still gives the same issues. I tried a different approach on reading the image
fullImage = Toolkit.getDefaultToolkit().getImage(new File(rotateURL).getAbsolutePath());
leftImage = rotatePicture(fullImage, 90);
but still the problem remains. So there seems to be a problem with the reading of the image, are there any other ways I didn't think about while reading the image?