package cn.jason.ios.images;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyImageIcon extends JFrame {
/** 打開本地文件選擇對話框,返回圖片絕對路徑 */
private static String getLocalImageAbsolutePath() {
Frame frame = new Frame();
FileDialog dialog = new FileDialog(frame, "選擇圖片", FileDialog.LOAD);
dialog.setBounds(300, 100, 500, 450);
dialog.setVisible(true);
String dir = dialog.getDirectory();
String file = dialog.getFile();
if (dir == null || file == null) return "NO-Path";
return dir + file;
}
/** 退出程序 */
private static void exitProgram() {
System.exit(0);
}
/** 讀取圖片文件為字節數組(最大 10MB) */
private static byte[] getImageBytes(String imagePath) {
byte[] buffer = new byte[1024 * 1024 * 10];
File imageFile = new File(imagePath);
try (FileInputStream fis = new FileInputStream(imageFile)) {
int len = fis.read(buffer);
if (len > 0 && len < buffer.length) {
byte[] exact = new byte[len];
System.arraycopy(buffer, 0, exact, 0, len);
return exact;
}
return len > 0 ? buffer : null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/** 五種構建 ImageIcon 的方式 */
private static ImageIcon createIcon(byte[] data) { return new ImageIcon(data); }
private static ImageIcon createIcon(String path) { return new ImageIcon(path); }
private static ImageIcon createIcon(URL url) { return new ImageIcon(url); }
private static ImageIcon createIcon(Image img) { return new ImageIcon(img); }
/** 圖片縮放 */
private static ImageIcon scaleIcon(ImageIcon icon, int width, int height) {
Image img = icon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH);
return new ImageIcon(img);
}
/** 主程序演示 */
public static void main(String[] args) {
String path = getLocalImageAbsolutePath();
System.out.println("選中路徑: " + path);
MyImageIcon frame = new MyImageIcon();
frame.setBounds(200, 100, 500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
label.setBounds(100, 100, 300, 300);
// 鏈式調用:文件→字節→Icon→縮放
ImageIcon icon = scaleIcon(createIcon(getImageBytes(path)), 300, 300);
label.setIcon(icon);
frame.add(label);
frame.setVisible(true);
exitProgram();
}
}
byte[]:數據庫 BLOB、網絡流、內存處理String:本地文件路徑、Classpath 資源URL:網絡圖片、Jar 內資源(getClass().getResource())Image:BufferedImage 繪製、過濾器處理後的圖像// SCALE_SMOOTH 質量優先,SCALE_FAST 速度優先,SCALE_AREA_AVERAGING 面積平均 Image scaled = original.getScaledInstance(targetW, targetH, Image.SCALE_SMOOTH);
注意:getScaledInstance 返回的 Image 需重新包裝為 ImageIcon 才能在 Swing 組件中顯示。
使用 AWT FileDialog 而非 Swing JFileChooser,優勢:原生系統對話框、體驗一致、代碼簡潔。缺點:無法自定義文件過濾器、預覽功能。
ImageIO 實現格式轉換(JPG↔PNG↔WebP)