JSP空间欢迎您!专业JSP虚拟主机提供商!!!
返回首页
当前位置: 主页 > JSP教程 >

上传图片的缩放处理-非常实用!(感谢loveyourv

时间:2011-01-30 12:05来源:佚名 编辑:www.jspzg.com 点击: 次   字体大小:[ ]

当前阅读得是【JSP教程】之上传图片的缩放处理-非常实用!(感谢loveyourv!
【关键字信息】:上传,传图,图片,片的,的缩
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());
        }
    }
}
标签:
顶一下
(2)
100%
踩一下
(0)
0%
------分隔线----------------------------
【郑重声明】JSP中国刊载此文不代表同意其说法或描述,仅为提供更多信息,也不构成任何投资或其他建议。本网站有部分文章是由网友自由上传。对于此类文章本站仅提供交流平台,不为其版权负责。如果您发现本网站上有侵犯您的知识产权的文章,请联系我们,我们将及时删除,谢谢!
推荐内容