android 图片压缩,可压缩至任意大小(高和宽)

参考了网上的大侠们的压缩方法,但觉得不尽人意,所以自己写了一个压缩方法,如下:

本人亲测,压缩一张400多k,   2592*1552的图片,

将k设为50(因为要取得缩略图),压缩之后图片7k,大小为81*48

有少许偏差,因为在计算过程中double与int的转换及int的运算都会出现四舍五入的情况

/**
     * 压缩图片
     * @param s--图片所在路径
     * @param k--缩放后图片(目标图片)的宽或高
     * savePath--缩放后图片的存储路径
     * @return
     */
    public Bitmap scalePicture(String s,String savePath, int k){
    Bitmap bitmap=null;
    try{
    BitmapFactory.Options options =new BitmapFactory.Options(); 
       options.inJustDecodeBounds =true; 
       // 获取这个图片的宽和高 
       bitmap =BitmapFactory.decodeFile(s, options); //此时返回bm为空


       int be = 0;
be= (int)Math.sqrt((options.outHeight/k)*(options.outWidth/k)); 
if (be <= 1) 
      be = 1; 
       options.inJustDecodeBounds =false; 
       options.inSampleSize = be; 


       //重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false
       bitmap=BitmapFactory.decodeFile(s,options); 
       System.out.println("be----------------->"+be);
       
       //保存入sdCard  
               File file2= new File(savePath);  
               try {  
           FileOutputStream out = new FileOutputStream(file2);  
           if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)){  
               out.flush();  
               out.close();  
           }  
        } catch (Exception e) {  
           // TODO: handle exception  
        return null;
       }  
           
    }catch(Exception e){
    e.printStackTrace();
    return null;
    }
        return bitmap;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值