Java中如何根據圖片檔案建立Image物件,且將Image物件儲存為檔案形式
一.建立與儲存
1.根據一個檔案路徑建立Image物件
Image image = ImageIO.read(new File(filepath));
2.將Image物件儲存為檔案形式
BufferedImage image = ImageIO.read(new File(filepath));//要想儲存這個物件的話你要把image宣告為BufferedImage 型別
ImageIO.write(image, "jpg", new File("f:/image/apple.jpg"));
二.在影象介面中顯示影象
1.使用視窗載入,將圖片變為背景顯示
ImageIcon bg =new ImageIcon(image);
JLabel jl = new JLabel(bg);
jl.setBounds(0,0,bg.getIconWidth(),bg.getIconHeight());
jf.setSize(bg.getIconWidth(), bg.getIconHeight());
jf.setResizable(false);
//將圖片新增到分層窗格的最底層作為背景
jf.getLayeredPane().add(jl, new Integer(Integer.MIN_VALUE));
//內容窗格轉化為JPanel,否則不能設定為透明
JPanel jp = (JPanel)getContentPane();
jp.setLayout(null);
jp.setOpaque(false);//設定為透明
2.使用Graphics畫筆將圖片畫在視窗中
重寫窗體類的paint(Graphics g)方法
public void paint(Graphics g){
g.drawImage(0,0,400,300,null); //該方法的主體是視窗
}
當然也可以自己寫一個畫圖的方法
public void draw(Graphics g){
g.drwaImage(0,0,400,300,null); //記得傳一個Graphics畫筆進來
}
3.關於Graphics 物件為null的解決
(1)paint系列方法裡的是jre建立的
(2)當前類繼承了jframe的話直接可以這樣寫的graphics g=getgraphics();
(3)其他情況通過 Graphics g =new Graphics();出來的物件為null,應該採用下面方法:
BufferedImage bi = new BufferedImage(120,120, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bi.createGraphics();