日期:2014-05-20 浏览次数:20732 次
import javax.swing.*; import javax.imageio.*;; import java.awt.*; import java.awt.geom.*; import java.io.*; public class TestTh extends JFrame{ public static void main(String[] args){ TestTh t = new TestTh(); t.setSize(600, 400); t.setVisible(true); t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); t.add(new Thumbnail("G:\\Image\\image.jpg")); } } class Thumbnail extends JComponent{ private Image img; double ratio; String path; private AffineTransform af = AffineTransform.getScaleInstance(1,1); public Thumbnail(){ setSize(180, 200); } public void setPath(String path){ this.path = path; } public Thumbnail(String path){ this.path = path; setSize(180, 200); setImage(); } private void setImage(){ try{ img = ImageIO.read(new File(path)); ratio = culculateRatio(img.getWidth(null),img.getHeight(null)); //paintImmediately(getBounds()); }catch(IOException ex){ System.out.println("Can not find this file!"); } //paintImmediately(getBounds()); concateZoom(ratio); } private void concateZoom(double scale){ if (img==null)return; af.preConcatenate(AffineTransform.getScaleInstance(scale,scale)); paintImmediately(getBounds()); System.out.println(getWidth() + "&" + getHeight());//此处输出180 & 200 } @Override protected void paintComponent(Graphics g) { System.out.println(getWidth() + "*" + getHeight());//此处输出1 * 1,最终画出的图只有一个点 super.paintComponent(g); if (img==null) { g.setColor(Color.BLACK); g.fillRect(0,0,getWidth(),getHeight()); } else { Graphics2D g2d = (Graphics2D)g; g2d.setTransform(af); g2d.drawImage(img, (int)(((getWidth()-img.getWidth(null)*ratio)/2)/ratio), (int)(((getHeight()-img.getHeight(null)*ratio)/2)/ratio), this); } }//paintComponent final double culculateRatio(int width, int height){//计算缩放比率 //System.out.println(getWidth() + "*" + getHeight()); if(getWidth()>=width && getHeight()>=height) return 1; if((double)getWidth()/width > (double)getHeight()/height) return (double)getHeight() / height; else return (double)getWidth() / width; }//culculateRatio }//Thumbnail