Lớp ImageIcon là một triển khai của giao diện Biểu tượng vẽ các Biểu tượng từ Hình ảnh. Bạn có thể hiển thị hình ảnh trên cửa sổ Swing bằng cách sử dụng lớp này, hàm tạo của lớp này chấp nhận một đối tượng BufferedImage làm tham số.
Do đó, để hiển thị hình ảnh OpenCV được lưu trữ trong đối tượng Mat bằng cửa sổ Swing, bạn cần chuyển đổi nó thành đối tượng BufferedImage và chuyển nó dưới dạng tham số cho phương thức ImageIcon.
Ví dụ
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
public class DisplayingImagesUsingSwings {
public static void main(String args[]) throws Exception {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading the Image from the file
String file = "D:\\images\\tree.jpg";
Mat image = Imgcodecs.imread(file);
//Encoding the image
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", image, matOfByte);
//Storing the encoded Mat in a byte array
byte[] byteArray = matOfByte.toArray();
//Preparing the Buffered Image
InputStream in = new ByteArrayInputStream(byteArray);
BufferedImage bufImage = ImageIO.read(in);
//Instantiate JFrame
JFrame frame = new JFrame();
//Set Content to the JFrame
frame.getContentPane().add(new JLabel(new ImageIcon(bufImage)));
frame.pack();
frame.setVisible(true);
System.out.println("Image Loaded");
}
} Đầu ra
Khi thực thi, chương trình trên tạo ra kết quả sau -