更新時(shí)間:2022-04-12 10:39:34 來源:動(dòng)力節(jié)點(diǎn) 瀏覽7070次
我們可以在 Java 中使用多種方式顯示圖像。下面我們將看到如何使用兩種方法在 Java 中顯示圖像。
在第一個(gè)示例中,我們使用JLabelSwing 庫的類。JLabelextends JComponent,我們可以將此組件附加到JFrame. 要讀取圖像文件,我們使用Java File類并傳遞圖像的路徑。接下來,我們BufferedImage使用 將圖像轉(zhuǎn)換為對象ImageIO.read()。現(xiàn)在我們創(chuàng)建一個(gè)圖標(biāo)以顯示在JLabel.
為了顯示標(biāo)簽圖標(biāo),我們需要一個(gè)大小為 500 x 500 的JFrame對象FlowLayout。大小可以根據(jù)我們的需要進(jìn)行調(diào)整。現(xiàn)在我們創(chuàng)建一個(gè)對象并使用函數(shù)JLabel設(shè)置它的圖標(biāo)。JLabel.setIcon()然后我們添加jLabel組件jFrame并將框架的可見性設(shè)置為true。
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class DisplayImage {
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\User1\\Pictures\\Camera Roll\\java.png");
BufferedImage bufferedImage = ImageIO.read(file);
ImageIcon imageIcon = new ImageIcon(bufferedImage);
JFrame jFrame = new JFrame();
jFrame.setLayout(new FlowLayout());
jFrame.setSize(500, 500);
JLabel jLabel = new JLabel();
jLabel.setIcon(imageIcon);
jFrame.add(jLabel);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
輸出:
在這個(gè)程序中,我們使用了一個(gè)強(qiáng)大的圖像處理庫,叫做ImageJ. 要使用它,我們首先將 maven 存儲(chǔ)庫和依賴項(xiàng)導(dǎo)入pom.xml.
<repositories>
<repository>
<id>scijava.public</id>
<url>https://maven.scijava.org/content/groups/public</url>
</repository>
</repositories>
<dependency>
<groupId>net.imagej</groupId>
<artifactId>ij</artifactId>
<version>1.53j</version>
</dependency>
我們的目標(biāo)是展示一張圖片,ImageJ讓我們覺得它很簡單。openImage()以下是我們首先從類中調(diào)用靜態(tài)函數(shù)IJ并將其中圖像的路徑作為參數(shù)傳遞的代碼。請注意,我們只寫了帶有擴(kuò)展名的圖像名稱,因?yàn)槲覀兊膱D像位于同一目錄中。
IJ.openImage()返回一個(gè)ImagePlus對象imagePlus。現(xiàn)在我們使用對象調(diào)用show()方法。imagePlus我們可以看到輸出顯示了幀中的圖像。
import ij.IJ;
import ij.ImagePlus;
public class DisplayImage {
public static void main(String[] args) {
ImagePlus imagePlus = IJ.openImage("mountains.jpeg");
imagePlus.show();
}
}
輸出:
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級 202925
初級 203221
初級 202629
初級 203743