如何在Java Swing中将ImageIcon旋转一定的度数?

fcg9iug3  于 2022-11-20  发布在  Java
关注(0)|答案(1)|浏览(156)

我需要在Java中旋转ImageIcon到缓冲图像。我已经尝试了所有可能的方法,有没有方法,我已经尝试过将ImageIcon转换为bufferedImage。
我尝试了所有可能的StackOverflow方案

cxfofazt

cxfofazt1#

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));

            // Add rotated image
            icon.setImage(image = rotated);

            // Repaint
            label.revalidate();
            label.repaint();
        }

        // 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;
        }
    }
}

相关问题