Here's a little example that reads and rotates an image 90 degrees.
private String rotateImage(String pathToImage) { BufferedImage image = null; String tempFileName = null; try { File f = new File(pathToImage); if (f.exists()) { image = ImageIO.read(f); Image rotatedImage = new BufferedImage(image.getHeight(), image.getWidth(),image.getType()); Graphics2D g2d = (Graphics2D) rotatedImage.getGraphics(); g2d.rotate(Math.toRadians(90.0)); g2d.drawImage(image, 0, -rotatedImage.getWidth(null), null); g2d.dispose(); //Random name String timeStampName = UUID.randomUUID(). toString().substring(1, 8); //Save image to java.io.tmpdir tempFileName = System.getProperty("java.io.tmpdir") + timeStampName + ".jpg"; ImageIO.write((BufferedImage) rotatedImage, "jpg", new File(tempFileName)); } } catch (Exception e) { //TODO: Do something here } return tempFileName; }
Your code example change the type of the target image. Isn't it better to use the source image type for the target one?
ReplyDeleteImage rotatedImage = new BufferedImage(image.getHeight(),
image.getWidth(), image.getType());
Yes, you are correct :)
ReplyDeleteI was using this example and I should have corrected that since this issue was already mentioned before in previous posts :)
Thanks for the feedback.