学习Java中 awt和ImageIO时,遇到了如下问题 :
在用ImageIO.read()方法读取图片并通过BufferedImage展示在Frame上时,显示图片大小和我设置的Frame窗口大小不一致,导致不能正确显示图片 ,如图 :
代码如下 :
javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageIOPractice {
Frame frame = new Frame("位图读写");
MenuBar menuBar = new MenuBar();
Menu menu = new Menu("文件");
MenuItem open = new MenuItem("打开");
MenuItem save = new MenuItem("另存为");
//声明BufferedImage对象记录读取的图片
BufferedImage image ;
private class myCanvas extends Canvas{
@Override
public void paint(Graphics g) {
g.drawImage(image,0,0,null);
}
}
myCanvas drawArea = new myCanvas();
public void init(){
open.addActionListener(e->{
//lamada表达式
//打开文件对话框
FileDialog fileDialog = new FileDialog(frame,"打开图片",FileDialog.LOAD);
fileDialog.setVisible(true);
//获取图片路径及名称
String fileName = fileDialog.getFile();
String directory = fileDialog.getDirectory();
try {
image = ImageIO.read(new File(directory,fileName));
drawArea.repaint();
} catch (IOException ex) {
ex.printStackTrace();
}
});
save.addActionListener(e -> {
FileDialog fileDialog = new FileDialog(frame,"保存图片",FileDialog.SAVE);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String fileName = fileDialog.getFile();
try {
ImageIO.write(image,"jpg",new File(directory,fileName));
} catch (IOException ex) {
ex.printStackTrace();
}
});
menu.add(open);
menu.add(save);
menuBar.add(menu);
frame.setMenuBar(menuBar);
frame.add(drawArea);
frame.setBounds(200,200,700,500);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setVisible(true);
}
public static void main(String[] args) {
new ImageIOPractice().init();
}
}
求解决方法