📜  java swing pic - Java (1)

📅  最后修改于: 2023-12-03 15:01:32.463000             🧑  作者: Mango

Java Swing Pic

Java Swing Pic是基于Java Swing库的图片浏览器,支持常见的图片格式,并提供了基本的操作功能,如旋转、缩放、剪切、保存等。

开发环境
  • Java 8
  • Eclipse Oxygen或更高版本
安装
  1. 打开Eclipse,选择File -> New -> Java Project,输入项目名称并点击Finish。
  2. 右键点击项目名称,选择Build Path -> Configure Build Path。
  3. 在弹出的对话框中,选择Libraries选项卡,点击Add Library。
  4. 选择User Library,点击Next。
  5. 点击New,输入一个名称(如Swing),点击OK。
  6. 选择新建的库,点击Add External JARs,选择swing库的jar包(通常在安装目录中的lib文件夹下)。
  7. 点击OK,完成库的添加。
使用
  1. 创建一个JFrame类,并设置标题和大小。
import javax.swing.JFrame;

public class MyFrame extends JFrame {
    public MyFrame() {
        setTitle("Java Swing Pic");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new MyFrame();
    }
}
  1. 在JFrame中添加一个JPanel,用于显示图片。
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.io.File;
import javax.swing.JPanel;

public class ImagePanel extends JPanel {
    private Image image;
    
    public ImagePanel(String filename) {
        MediaTracker mt = new MediaTracker(this);
        image = Toolkit.getDefaultToolkit().getImage(filename);
        mt.addImage(image, 0);
        
        try {
            mt.waitForAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        setPreferredSize(new Dimension(image.getWidth(this), image.getHeight(this)));
    }
    
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}
  1. 在JPanel中添加鼠标事件,实现图片的操作功能。
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class ImagePanel extends JPanel {
    private Image image;
    private BufferedImage bufferedImage;
    private double scale = 1.0;
    
    public ImagePanel(String filename) {
        MediaTracker mt = new MediaTracker(this);
        image = Toolkit.getDefaultToolkit().getImage(filename);
        bufferedImage = loadImage(filename);
        mt.addImage(image, 0);
        
        try {
            mt.waitForAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        setPreferredSize(new Dimension(image.getWidth(this), image.getHeight(this)));
        
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) { // 左键
                    int clickCount = e.getClickCount();
                    if (clickCount == 2) { // 双击
                        rotateImage(90);
                    }
                }
            }
        });
        
        addMouseWheelListener(e -> {
            if (e.getWheelRotation() < 0) { // 向上滚动
                scaleImage(1.1);
            } else { // 向下滚动
                scaleImage(0.9);
            }
        });
    }
    
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, (int) (scale * image.getWidth(this)), (int) (scale * image.getHeight(this)), this);
    }
    
    private BufferedImage loadImage(String filename) {
        BufferedImage img = null;
        try {
            img = ImageIO.read(new File(filename));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return img;
    }
    
    private void rotateImage(int angle) {
        AffineTransform transform = new AffineTransform();
        transform.rotate(Math.toRadians(angle), bufferedImage.getWidth() / 2, bufferedImage.getHeight() / 2);
        AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC);
        bufferedImage = op.filter(bufferedImage, null);
        image = bufferedImage.getScaledInstance((int) (scale * bufferedImage.getWidth()), (int) (scale * bufferedImage.getHeight()), Image.SCALE_SMOOTH);
        repaint();
    }
    
    private void scaleImage(double factor) {
        scale *= factor;
        image = bufferedImage.getScaledInstance((int) (scale * bufferedImage.getWidth()), (int) (scale * bufferedImage.getHeight()), Image.SCALE_SMOOTH);
        repaint();
    }
    
    public void saveImage() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith(".jpg") || f.getName().toLowerCase().endsWith(".png") || f.getName().toLowerCase().endsWith(".bmp");
            }
            
            public String getDescription() {
                return "JPEG (*.jpg,*.jpeg,*.jpe)\n" + "PNG (*.png)\n" + "BMP (*.bmp)\n";
            }
        });
        
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            String formatName = getFileExtension(file);
            try {
                ImageIO.write(bufferedImage, formatName, file);
                JOptionPane.showMessageDialog(this, "保存成功", "信息", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "保存失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    private String getFileExtension(File file) {
        String fileName = file.getName();
        if (fileName.lastIndexOf('.') != -1 && fileName.lastIndexOf('.') != 0) {
            return fileName.substring(fileName.lastIndexOf('.') + 1);
        } else {
            return "";
        }
    }
}
  1. 在JFrame的构造函数中,将ImagePanel添加到JFrame中。
import javax.swing.JFrame;

public class MyFrame extends JFrame {
    public MyFrame() {
        setTitle("Java Swing Pic");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        
        ImagePanel panel = new ImagePanel("test.jpg");
        add(panel, BorderLayout.CENTER);
        
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new MyFrame();
    }
}
  1. 运行程序,即可看到一张图片在窗口中显示,鼠标左键双击可旋转图片,鼠标滚轮可缩放图片,右键保存图片。
结论

Java Swing Pic是一个基于Java Swing库的图片浏览器,提供了基本的操作功能,如旋转、缩放、剪切、保存等。开发者可以根据自己的需求,自由地对其进行扩展,使其更加强大和易用。