·您的位置: 首页 » 资源教程 » 编程开发 » JAVA、JSP » 上传图片的缩放处理 - 非常实用!(感谢loveyourvv兄弟)

上传图片的缩放处理 - 非常实用!(感谢loveyourvv兄弟)

类别: JAVA教程  评论数:0 总得分:0
import java.io.File;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.awt.image.AffineTransformOp;
import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;

public class UploadImg {
    
    String fromdir;            // fromdir 图片的原始目录
    String todir;            // todir 处理后的图片存放目录
    String imgfile;            // imgfile 原始图片
    String sysimgfile;        // sysimgfile 处理后的图片文件名前缀

    UploadImg( String fromdirNow, String todirNow, String imgfileNow, String sysimgfileNow ){
        fromdir = fromdirNow;
        todir = todirNow;
        imgfile = imgfileNow;
        sysimgfile = sysimgfileNow;
    }

    public boolean CreateThumbnail() throws Exception
        {
        // fileExtNmae是图片的格式 gif JPG 或png
        // String fileExtNmae="";
        double Ratio = 0.0;
        File F = new File(fromdir,imgfile);
        if ( !F.isFile() )
            throw new Exception(F+" is not image file error in CreateThumbnail!");
        
        //首先判断上传的图片是gif还是JPG ImageIO只能将gif转换为png
        // if (isJpg(imgfile)){
        //    fileExtNmae="jpg";
        //    }
        //else{
        //    fileExtNmae="png";
        //    }
        File ThF = new File( todir, sysimgfile + ".jpg" );
        
        BufferedImage Bi = ImageIO.read(F);
        //假设图片宽 高 最大为120 120
        Image Itemp = Bi.getScaledInstance (120,120,Bi.SCALE_SMOOTH);
        
        if ((Bi.getHeight()>120) || (Bi.getWidth()>120)){
            if (Bi.getHeight()>Bi.getWidth())
                Ratio = 120.0/Bi.getHeight();
            else
                Ratio = 120.0/Bi.getWidth();
            }
        
        AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(Ratio, Ratio), null);
        Itemp = op.filter(Bi, null);
        try {
            ImageIO.write((BufferedImage)Itemp, "jpg", ThF);
            }
        catch (Exception ex) {
            throw new Exception(" ImageIo.write error in CreatThum.: "+ex.getMessage());
            }
        return (true);
    }

    public static void main(String[] args)
    {
        UploadImg UI;
        boolean ss = false;

        try{
            UI = new UploadImg( "d://javalearn", "d://javalearn", "ps_high.jpg", "ps_low" );
            ss = UI.CreateThumbnail();
            if ( ss ) {
                System.out.println( "Success" );
                }
            else{
                System.out.println( "Error" );
                }
        }
        catch(Exception e){
            System.out.print(e.toString());
        }
    }
}


-= 资 源 教 程 =-
文 章 搜 索
关键词:
类型:
范围:
纯粹空间 softpure.com
Copyright © 2006-2008 暖阳制作 版权所有
QQ: 15242663 (拒绝闲聊)  Email: faisun@sina.com
 纯粹空间 - 韩国酷站|酷站欣赏|教程大全|资源下载|免费博客|美女壁纸|设计素材|技术论坛   Valid XHTML 1.0 Transitional
百度搜索 谷歌搜索 Alexa搜索 | 粤ICP备19116064号-1