Java 加载图片的两种方法 - coffeescript

时间:2024-03-12 13:02:29

Java 加载图片的两种方法

2012-10-26 00:56  coffeescript  阅读(26162)  评论(0编辑  收藏  举报

1.使用Toolkit.getDefaultToolkit().getImage()方法

View Code
 1 View Code 
 2 
 3 import javax.swing.JFrame;
 4 import java.awt.*;
 5 import java.awt.event.*;
 6 
 7 public class TestLoadImage{
 8     public static void main(String[] args){
 9         JFrame f=new JFrame();
10         MyCanvas mc=new MyCanvas();
11         Image image=Toolkit.getDefaultToolkit().getImage("a.PNG");
12         mc.setImage(image);
13         f.add(mc);
14         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15         f.setSize(400,550);
16         f.setVisible(true);
17     }
18 }
19 
20 class MyCanvas extends Canvas {
21     private Image in;
22     private int image_width;
23     private int image_height;
24     
25     public void setImage(Image in){
26         this.in=in;
27     }
28     
29     public void paint(Graphics g){
30         g.drawImage(in,0,0,this.getWidth(),this.getHeight(),this);
31     }    
32 }

 

2.使用BufferedImage类加载,BufferedImage类基础了Image类

View Code
 1 View Code 
 2 
 3 import java.awt.*;
 4 import java.awt.image.*;
 5 import javax.swing.JFrame;
 6 import java.io.*;
 7 import javax.imageio.*;
 8 
 9 
10 public class TestBufferedImage extends Canvas{
11     
12     public static void main(String[] args){
13         JFrame f=new JFrame();
14         MyCanvas mc=new MyCanvas();
15         f.add(mc);
16         try{
17             File file=new File("a.PNG");
18             BufferedImage bi=ImageIO.read(file);
19             mc.setImage(bi);
20         }catch(Exception e){
21             e.printStackTrace();
22         }
23         mc.repaint();
24         f.setSize(400,550);
25         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
26         f.setVisible(true);
27     }
28 }
29 
30 class MyCanvas extends Canvas{
31     private BufferedImage bi;
32     private Image im;
33     private int image_width;
34     private int image_height;
35     
36     public void setImage(BufferedImage bi){
37         this.bi=bi;
38         this.zoom();
39     }
40     
41     public void paint(Graphics g){
42         g.drawImage(im,0,0,this.getWidth(),this.getHeight(),this);
43     }
44     
45     public void zoom(){
46         image_width=bi.getWidth();
47         image_height=bi.getHeight();
48         im=bi.getScaledInstance(image_width,image_height,Image.SCALE_SMOOTH);
49     }
50 }

 

两种方法都会遇到一个问题,就是随着窗口改变,图片大小固定不变,要想实现图片随窗口大小改变,只需要

g.drawImage(im,0,0,this.getWidth(),this.getHeight(),this);

 

在使用BufferedImage加载图片时需要调用其getScaledInstance()方法创建一个新Image对象,否则图像无法显示在画布上。