随笔-179  评论-666  文章-29  trackbacks-0
方法1:
缩略图只要10行代码就够了,前面介绍过N次了.自己不能往前找找吗?

Image src = ToolKit.getToolKit().createImage("文件路径");
然后先生成一个BufferedImage bi作为画布.
BufferedImage bi = new BufferedImage(目标宽, 目标高,BufferedImage.TYPE_INT_RGB);
得到它的Graphics对象:
Graphics g = bi.getGraphics();
然后往这个画而上画原图就行了:
g.grawImage(src,0,0,目标宽,目标高,null);
找一个编码类,如JPEGEncoder,GIFEncoder
把bi编码输出就行了.

方法2:
import javax.imageio.ImageIO;
import javax.imageio.IIOException;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.io.File;
import java.awt.image.AffineTransformOp;
import java.awt.geom.AffineTransform;

public class Test {

    public static void main (String argv[]) {
        try {
            File fi = new File("C:/1.jpg"); //大图文件
            File fo = new File("C:/2.jpg"); //将要转换出的小图文件

            AffineTransform transform = new AffineTransform();
            BufferedImage bis = ImageIO.read(fi);

            int w = bis.getWidth();
            int h = bis.getHeight();
            double scale = (double)w/h;

            int nw = 120;
            int nh = (nw * h) / w;
            if(nh>120) {
                nh = 120;
                nw = (nh * w) / h;
            }

            double sx = (double)nw / w;
            double sy = (double)nh / h;

            transform.setToScale(sx,sy);

            AffineTransformOp ato = new AffineTransformOp(transform, null);
            BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
            ato.filter(bis,bid);
            ImageIO.write(bid, "jpeg", fo);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

posted on 2007-08-08 08:51 Alpha 阅读(1501) 评论(1)  编辑  收藏 所属分类: Java J2EE JSP

评论:
# re: [ZT]java生成缩略图代码 2009-02-08 12:43 | allforjava
这个图片还是失真 了 没办法按照原来的清晰度生成吗?  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: