- UID
- 1576
- 帖子
- 6066
- 积分
- 8620
- 阅读权限
- 60
- 注册时间
- 2005-7-14
- 最后登录
- 2010-3-24
- 在线时间
- 1266 小时
|
import javax.swing.*;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
public class PhotoViewArea extends JPanel {
public PhotoViewArea() {
super();
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
;
c.anchor = GridBagConstraints.NORTH;
JScrollPane photoPane = new JScrollPane(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
photoPanel.setPreferredSize(new Dimension(500, 600));
photoPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 4));
//加入图片
for (int i = 0; i < 8; i++) {
String filePath = "d:/DSC0013" + i + ".jpg";
String newFilePath = i + ".jpg";
addPhoto(filePath, newFilePath);
}
photoPane.setViewportView(photoPanel);
this.add(photoPane, c);
}
public void addPhoto(String filePath, String newFilePath) {
int wideth = 100;
int height = 100;
try {
File _file = new File(filePath); // 读入文件
Image src = javax.imageio.ImageIO.read(_file); // 构造Image对象
BufferedImage tag = new BufferedImage(wideth, height,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src, 0, 0, wideth, height, null); // 绘制缩小后的图
FileOutputStream out = new FileOutputStream(newFilePath); // 输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // 近JPEG编码
out.close();
} catch (Exception e) {
// TODO: handle exception
}
ImageIcon icon = new ImageIcon(newFilePath);
icon.setImage(icon.getImage().getScaledInstance(wideth, height,Image.SCALE_FAST));//设置图片大小
JLabel l = new JLabel("fileName", icon, SwingConstants.CENTER);
l.setVerticalTextPosition(JLabel.BOTTOM);
l.setHorizontalTextPosition(JLabel.CENTER);
l.setBorder(BorderFactory.createLineBorder(Color.BLACK));
photoPanel.add(l);
}
JPanel photoPanel = new JPanel();
public static void main(String[] args) {
JFrame f = new JFrame("");
JPanel p = new PhotoViewArea();
f.getContentPane().add(p);
f.pack();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
f.setVisible(true);
}
} |
|