图片缩略图的实现,比较灵活[可直接使用]

27 篇文章 0 订阅

其中

originalPath是图片源地址,

newPath是生成缩略图的目的地址,

newWidth、newHeight为缩略图的宽度和高度。

看代码

//改变图像宽和高,维持宽高比   
public static void changeImagePixel(String originalPath,String newPath,int newWidth,int newHeight){   
    //读入内存   
    BufferedImage bi=null;   
    try {   
        bi = ImageIO.read(new File(originalPath));   
           
        //原始宽、高   
        int originalWidth=bi.getWidth();   
        int originalHeight=bi.getHeight();   
        //宽、高比,默认1,即新宽、高和原始宽、高一样   
        double ratio=1;   
           
        //原始宽、高比,最终将维持该比例   
        double originalRatio=(double)originalWidth/originalHeight;   
           
        //文件后缀名   
        String fileType = originalPath.substring(originalPath.lastIndexOf("."));   
        String newFileType="jpg";   
        if(fileType.equals("png") || fileType.equals("PNG")){   
            newFileType="png";   
        }   
           
        //如果图片宽度或者高度超出给定范围   
        if(originalWidth>newWidth || originalHeight>newHeight){   
            if(newWidth < (int)(Math.floor(newHeight * originalRatio))){   
                //以宽度为准,高度自动,维持原始比例   
                ratio = (double)newWidth / originalWidth;   
            } else {   
                //以高度为准,宽度自动,维持原始比例   
                ratio = (double)newHeight / originalHeight;   
            }   
        }   
           
        AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);   
        Image newImage = op.filter(bi, null);   
        try {   
            //如果目录不存在,则创建   
            //File newPathDir=new File(newPath.substring(0,newPath.lastIndexOf("\\")+1));   
            //if(!newPathDir.exists()) newPathDir.mkdirs();   
               
            ImageIO.write((BufferedImage) newImage, newFileType, new File(newPath));   
        } catch (IOException e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        }   
    } catch (IOException e) {   
        // TODO Auto-generated catch block   
        e.printStackTrace();   
    } catch (Exception e) {   
        // TODO Auto-generated catch block   
        e.printStackTrace();   
    }   
}  


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值