ImageIO读取位图显示在Frame中

package cn.sisy.awt;
import javax.imageio.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class ZoomImage {
	// 下面两个常量设置缩小后图片的大小
	private final int WIDTH = 300;
	private final int HEIGHT = 300;
	// 定义个BuffedImage对象,用于保存缩小后的位图
	BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
			BufferedImage.TYPE_INT_RGB);
	Graphics g = image.getGraphics();
	private Frame frame = new Frame("显示图片");
	MyCanvas canvas = new MyCanvas();
	
	public void zoom() throws Exception {
		// 读取原始位图
		Image srcImage = ImageIO.read(new File("image/board.jpg"));
		// 将原始位图缩小后绘制到image图象中
		g.drawImage(srcImage, 0, 0, WIDTH, HEIGHT, null);
		// 将image图象文件输出到磁盘文件中。
		ImageIO.write(image, "jpeg", new File(System.currentTimeMillis()
				+ ".jpg"));
		canvas.setPreferredSize(new Dimension(300,300));
		//canvas.repaint();
		frame.add(canvas);
		frame.pack();
		frame.setVisible(true);
	}
	class MyCanvas extends Canvas{
		@Override
		public void paint(Graphics g) {
			g.drawImage(image,0,0,null);
		}
	}
	public static void main(String[] args) throws Exception {
		new ZoomImage().zoom();
	}
}

 程序运行如下:


ImageIO读取位图显示在Frame中_第1张图片

你可能感兴趣的:(JAVA,SE,java)