Home > Mobile >  How to rotate ImageIcon by a certain amount of degrees in Java Swing?
How to rotate ImageIcon by a certain amount of degrees in Java Swing?

Time:11-18

I need to rotate ImageIcon to buffered image in Java. I've tried every possible way, is there any way, I already tried to convert ImageIcon to bufferedImage.

I tried every possible StackOverflow solution

CodePudding user response:

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

public class Test {

    public static void main(String[] args) {
        // Create GUI
        GUI gui = new GUI();

        // Schedule task; rotate img every 1s
        Timer timer = new Timer(1000, e -> gui.rotateImg());
        timer.setRepeats(true);
        timer.start();
    }

    static class GUI extends JFrame {
        // Web url for image of cute doggo
        private static final String IMAGE_URL = "https://i.pinimg.com/736x/10/b2/6b/10b26b498bc3fcf55c752c4e6d9bfff7.jpg";

        // Cache image and UI components for rotation
        private BufferedImage image;
        private ImageIcon icon;
        private JLabel label;

        // Create new JFrame
        public GUI() {
            // Config grame
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(700, 700);
            setLocationRelativeTo(null);


            URL url;
            image = null;

            try {
                // Download   cache image from web
                url = new URL(IMAGE_URL);
                image = ImageIO.read(url);
            } catch (IOException e) {
                // Handle error downloading
                System.out.println("Failed to read image due to: "   e.getMessage());
            } finally {
                // On success - create/cache UI components
                if (image != null) {
                    // In this example I am using a label here to display an ImageIcon
                    // But at root the ImageIcon is holding a BufferedImage which is what we're modifying on rotation
                    add(label = new JLabel(icon = new ImageIcon(image)));
                }
            }

            // Show configured JFrame
            setVisible(true);
        }

        public void rotateImg() {
            if (image == null) return;

            // Rotate image
            BufferedImage rotated = rotateImg(image, Math.toRadians(90));
            image = rotated;

            // Add rotated image on ui thread
            SwingUtilities.invokeLater(() -> {
                icon.setImage(rotated);
                label.updateUI();
            });
        }

        // SRC: https://www.delftstack.com/howto/java/java-rotate-image/
        private BufferedImage rotateImg(BufferedImage img, double degrees) {
            int w = img.getWidth(), h = img.getHeight();

            BufferedImage imgCopy = new BufferedImage(w, h, img.getType());
            Graphics2D g2d = imgCopy.createGraphics();

            g2d.rotate(degrees, w / 2, h / 2);
            g2d.drawImage(img, null, 0, 0);

            return imgCopy;
        }
    }
}
  • Related