2014-03-27 141 views
1

我想從目錄加載圖像並將其作爲圖標放入JLabel。但是,當圖像尺寸很大時,它不能完全符合標籤。我嘗試調整圖像的大小以適應標籤,但不起作用。我可否知道我要去哪裏?調整圖像大小以適應JLabel

JFileChooser choose=new JFileChooser(); 
choose.showOpenDialog(null); 
File f=choose.getSelectedFile(); 
String filename=f.getAbsolutePath(); 
path.setText(filename); 

ImageIcon icon=new ImageIcon(filename); 
Image img=icon.getImage(); 
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); 
Graphics g = bi.createGraphics(); 
g.drawImage(img,500, 500, null); 
ImageIcon newIcon = new ImageIcon(bi); 
image_label.setIcon(newIcon); 
+0

啊,沒有。認真。請嘗試定義「最大」允許大小,並縮小任何太大的圖像。對於[示例](http://stackoverflow.com/questions/14548808/scale-the-imageicon-automatically-to-label-size/14553003#14553003)和[示例](http://stackoverflow.com/questions/ 11959758/java-maintain-aspect-ratio-of-jpanel-background-image/11959928#11959928) – MadProgrammer

+0

*「哪裏出錯了?」* - 首先創建一個BufferedImage,其大小與你剛剛加載的圖像,然後在畫布內繪製圖像500x500 ...除非圖像大於500x500,否則圖像將呈現出視野... – MadProgrammer

+0

@MadProgrammer我試着通過你給出的2個例子,並且我想承認我是處理圖像的新手,因此我無法理解發生了什麼。我的jLabel的大小是500x500,因此我將圖像縮放到500x500,並且我加載的圖像肯定比這個大, –

回答

1
BufferedImage img = ImageIO.read(...); 
Image scaled = img.getScaledInstance(500, 500, Image.SCALE_SMOOTH); 
ImageIcon icon = new ImageIcon(scaled); 

當心,這將縮放圖像,使其爲方形。看看Java: maintaining aspect ratio of JPanel background image,它討論了在縮放時保持圖像的高寬比。

此外,你應該閱讀The Perils of Image.getScaledInstance(),並看看Scale the ImageIcon automatically to label size它採用了分而conqure縮放algorithim和Quality of Image after resize very low -- Java這表明做了一個逐步調整的問題...

相關問題