Java原生窗体(JFrame/JPanel)显示图片(支持OpenCV)

为便于比对OpenCV处理前后图片效果,需要将原始图片、处理后的图片、OpenCV矩阵图像显示出来。
借鉴于网上的资料,在此处给出满足上述需求的工具类。

支持:拖拽自适应图片大小,通过文件路径、Mat、Image显示图片
备注:如果不需要显示OpenCV功能,直接删除该部分代码即可

参考资料:
https://stackoverflow.com/questions/13871307/jframe-not-showing-a-picture
https://www.cnblogs.com/superbool/p/5331196.html

OpenCV依赖(版本可以不一样):

<dependency>
    <groupId>org.opencv</groupId>
    <artifactId>opencv</artifactId>
    <version>3.3.0</version>
</dependency>

工具类:

import org.opencv.core.Mat;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

/**
 * 图片显示器
 * @author stonelu
 * @date 2019-04-30 17:20
 */
public class ImageForm {

    /**
     * 显示OpenCV矩阵图像
     * @param imageMat
     * @param size
     */
    public static void showImage(Mat imageMat, Dimension size) {
        showImage(mat2BufferedImage(imageMat), size);
    }

    /**
     * 显示指定文件路径图片
     * @param imagePath
     * @param size
     */
    public static void showImage(String imagePath, Dimension size) {
        showImage(new ImageIcon(imagePath).getImage(), size);
    }

    /**
     * 显示Image图片元素
     * @param image
     * @param size
     */
    public static void showImage(Image image, Dimension size) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setSize(size);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new PaintPanel(image, size));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    /**
     * 将OpenCV的Mat转换为Image
     * @param matrix
     * @return
     */
    private static Image mat2BufferedImage(Mat matrix) {
        int type = BufferedImage.TYPE_BYTE_GRAY;
        if (matrix.channels() > 1) {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }
        int bufferSize = matrix.channels() * matrix.cols() * matrix.rows();
        byte[] buffer = new byte[bufferSize];
        matrix.get(0, 0, buffer); // 获取所有的像素点
        BufferedImage image = new BufferedImage(matrix.cols(), matrix.rows(), type);
        final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        System.arraycopy(buffer, 0, targetPixels, 0, buffer.length);
        return image;
    }

    /**
     * 图片容器
     */
    private static class PaintPanel extends JPanel {

        private ImageIcon imageIcon;
        private Dimension size;

        public PaintPanel(Image image, Dimension size) {
            imageIcon = new ImageIcon(image);
            this.size = size;
        }

        @Override
        public Dimension getPreferredSize() {
            // 初识大小
            return size;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // 图片大小自适应,可拖拽
            g.drawImage(this.imageIcon.getImage(), 0, 0, this.getWidth(), this.getHeight(), imageIcon.getImageObserver());
        }
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在JFrame窗体中加载动态图片,可以使用JLabel组件和Timer类来实现。 以下是一个示例代码: ```java import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class DynamicImageFrame extends JFrame { private JLabel imageLabel; // 图片标签 private ImageIcon[] imageIcons; // 图片数组 private int currentIndex; // 当前图片索引 public DynamicImageFrame() { setTitle("动态图片"); setSize(500, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // 初始化图片数组 imageIcons = new ImageIcon[3]; imageIcons[0] = new ImageIcon("image1.jpg"); imageIcons[1] = new ImageIcon("image2.jpg"); imageIcons[2] = new ImageIcon("image3.jpg"); // 初始化图片标签 imageLabel = new JLabel(imageIcons[currentIndex]); imageLabel.setHorizontalAlignment(SwingConstants.CENTER); imageLabel.setVerticalAlignment(SwingConstants.CENTER); add(imageLabel, BorderLayout.CENTER); // 设置定时器,每隔一段时间切换图片 Timer timer = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { currentIndex = (currentIndex + 1) % imageIcons.length; imageLabel.setIcon(imageIcons[currentIndex]); } }); timer.start(); } public static void main(String[] args) { DynamicImageFrame frame = new DynamicImageFrame(); frame.setVisible(true); } } ``` 在上述代码中,首先定义了一个JLabel组件,用于显示图片。然后定义了一个ImageIcon数组,用于存储要显示图片。在构造函数中,将第一张图片添加到图片标签中,并使用Timer类每隔一段时间切换图片。在定时器的ActionListener中,通过改变数组索引和设置图片标签的图标来实现动态显示图片。最后在main方法中创建JFrame窗体显示出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值