1 package test;
2
3 import java.io.File;
4 import java.awt.image.BufferedImage;
5 import java.awt.Image;
6 import java.awt.image.AffineTransformOp;
7 import javax.imageio.ImageIO;
8 import java.awt.geom.AffineTransform;
9
10 public class UploadImg{
11
12 String fromdir; // fromdir 图片的原始目录
13
14 String todir; // todir 处理后的图片存放目录
15
16 String imgfile; // imgfile 原始图片
17
18 String sysimgfile; // sysimgfile 处理后的图片文件名前缀
19
20 UploadImg(String fromdirNow, String todirNow, String imgfileNow,
21 String sysimgfileNow){
22 fromdir = fromdirNow;
23 todir = todirNow;
24 imgfile = imgfileNow;
25 sysimgfile = sysimgfileNow;
26 }
27
28 public boolean CreateThumbnail() throws Exception {
29 // fileExtNmae是图片的格式 gif JPG 或png
30 // String fileExtNmae="";
31 double Ratio = 0.0;
32 File F = new File(fromdir, imgfile);
33 if (!F.isFile())
34 throw new Exception(F
35 + " is not image file error in CreateThumbnail!");
36 File ThF = new File(todir, sysimgfile + ".jpg");
37
38 BufferedImage Bi = ImageIO.read(F);
39 // 假设图片宽 高 最大为300 3000
40 Image Itemp = Bi.getScaledInstance(300, 300, Bi.SCALE_SMOOTH);
41
42 if ((Bi.getHeight() > 300) || (Bi.getWidth() > 300)){
43 if (Bi.getHeight() > Bi.getWidth())
44 Ratio = 300.0 / Bi.getHeight();
45 else
46 Ratio = 300.0 / Bi.getWidth();
47 }
48
49 AffineTransformOp op = new AffineTransformOp(AffineTransform
50 .getScaleInstance(Ratio, Ratio), null);
51 Itemp = op.filter(Bi, null);
52 try{
53 ImageIO.write((BufferedImage) Itemp, "jpg", ThF);
54 } catch (Exception ex){
55 throw new Exception(" ImageIo.write error in CreatThum.: "
56 + ex.getMessage());
57 }
58 return (true);
59 }
60
61 public static void main(String[] args){
62 UploadImg UI;
63 boolean ss = false;
64
65 try{
66 UI = new UploadImg("d:\\", "d:\\", "src.jpg", "ps_low1");
67 ss = UI.CreateThumbnail();
68 if (ss){
69 System.out.println("Success");
70 } else{
71 System.out.println("Error");
72 }
73 } catch (Exception e){
74 System.out.print(e.toString());
75 }
76 }
77 }
posted on 2007-08-22 11:05
Derek.Guo 阅读(2307)
评论(1) 编辑 收藏 所属分类:
Java