[英]Java JFileChooser .png files to byte[] black image
我需要將圖像.png上載到服務器並將其顯示到Swing GUI,我使用的是JFileChooser,用戶選擇一個.png圖像並將其存儲在byte []中。 稍后,當我嘗試顯示圖像時,圖像全為黑色。 .jpg文件不會發生這種情況。 我對.png圖像的透明度有疑問。 這是我的代碼:
將圖像保存到字節[]:
public byte[] AvatarToByte(String url){
byte[] data = null;
String extension = "";
try{
BufferedImage bImage = ImageIO.read(new File(url));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if(url.toString().toLowerCase().contains(".png")){
extension = "png";
}else{
extension = "jpg";
}
ImageIO.write(bImage, extension, bos );
data = bos.toByteArray();
}catch(Exception e){
e.printStackTrace();
}
return data;
}
從byte []到Java swing:
public ByteToAvatar(byte[] data){
BufferedImage img = null;
img = ImageIO.read(new ByteArrayInputStream(data));
JLabel lblURL = new JLabel();
lblURL.setBorder(new LineBorder(Color.GRAY));
lblURL.setBackground(SystemColor.controlLtHighlight);
lblURL.setBounds(10, 10, 80, 80);
lblURL.setIcon(Resize(img));
}
調整:
private ImageIcon Resize(Image img){
Image newImg = img.getScaledInstance(80, 80, Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(newImg);
return image;
}
編輯:嘗試在調整大小之前顯示圖像,並且顯示正確。 Resize(Image img)一定有問題。
我已經測試過您的代碼,並且可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.