日期:2014-05-20 浏览次数:20754 次
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class ImageTest {
public static void main(String args[]) {
new MyFrame();
}
}
class MyFrame extends JFrame{
JPanel panel = null;
JLabel label = null;
JPanel panel2 = null;
JLabel label2 = null;
public MyFrame(){
super("测试图片灰度值的熵值");
this.setBounds(400,100, 400, 400);
this.setBackground(Color.gray);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
System.exit(0);
}
});
JMenu fileMenu = new JMenu("选择图片");
JMenuItem openItem = new JMenuItem("打开");
openItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openFile();
}
}) ;
fileMenu.add(openItem);
JMenuBar bar = new JMenuBar();
bar.add(fileMenu);
this.setJMenuBar(bar);
this.panel = new JPanel();
this.label = new JLabel();
label.setText("请选择一张图片!");
panel.add(label);
this.panel2 = new JPanel();
this.label2 = new JLabel();
panel2.add(label2);
this.add(panel, BorderLayout.CENTER);
this.add(panel2, BorderLayout.SOUTH);
this.setVisible(true);
this.setResizable(true);
}
public void openFile() {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(this);
File f = chooser.getSelectedFile();
//文件是否存在或者是否选择
if(f == null) {
return;
}
BufferedImage bi = null;
try {
bi = ImageIO.read(f);
/*获取文件是否为图片,如果能够正常的获取到一张图片的宽高属性,
那肯定这是一张图片,因为非图片文件是获取不到它的宽高属性的*/
if(bi == null || bi.getHeight() <=0 || bi.getWidth() <=0){
label.setText("您选择的不是一张图片,请从新选择!");
return;
} else {
calculate(bi);
String path = f.getPath();
ImageIcon image = new ImageIcon(path);
label.setIcon(image); //设置JLabel的显示图片
label.setText("");
this.pack();
validate(); //使有效
}
} catch (IOException e) {
// e.printStackTrace();
return;
}
}
public void calculate(BufferedImage bi) {
int sgray[] = new int[256];
for(int i=0; i<256; i++) {
sgray[i] = 0;
}
double sum = 0;
int width = bi.getWidth();
int height = bi.getHeight();