java图片压缩

 /**
     * @param srcURL 原图地址
     * @param destURL 缩略图地址
     * @param extractBase 压缩基数
     * @param scale 压缩限制(宽/高)比例
     * @throws Exception
     */

 public static void extractPhoto (String srcURL, String destURL, int extractBase, int scale) throws Exception {

        
        File srcFile = new File (srcURL);
        Image src = ImageIO.read (srcFile);
        int srcHeight = src.getHeight (null);
        int srcWidth = src.getWidth (null);
        int deskHeight = 0;
        int deskWidth = 0;
        int srcScale = srcHeight / srcWidth;
        if (srcHeight > extractBase || srcWidth > extractBase) {
            if (srcScale >= scale || (srcScale != 0 && 1 / srcScale > scale)) {
                if (srcScale >= scale) {
                    deskHeight = extractBase;
                    deskWidth = srcWidth * deskHeight / srcHeight;
                } else {
                    deskWidth = extractBase;
                    deskHeight = srcHeight * deskWidth / srcWidth;

                }

  } else {
                if ( srcHeight > extractBase) {
                    deskHeight = extractBase;
                    deskWidth = srcWidth * deskHeight / srcHeight;
                } else {
                    deskWidth = extractBase;
                    deskHeight = srcHeight * deskWidth / srcWidth;
                }
            }
        } else {
            deskHeight = srcHeight;
            deskWidth = srcWidth;
            
        }
        BufferedImage tag = new BufferedImage (deskWidth, deskHeight, BufferedImage.TYPE_3BYTE_BGR);
        tag.getGraphics().drawImage(src.getScaledInstance(deskWidth, deskHeight,  Image.SCALE_SMOOTH), 0, 0,  null);   // tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist,  Image.SCALE_AREA_AVERAGING), 0, 0,  null);   

        FileOutputStream deskImage = new FileOutputStream (destURL); /
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder (deskImage);
        encoder.encode (tag);
        deskImage.close ();
    }

红色部分注明的两种方法压缩出来的图片文件较小,且清晰

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值