bitmap 将图片压缩到指定的大小 JAVA

  1. private void imageZoom() { 
  2.                 //图片允许最大空间   单位:KB 
  3.                 double maxSize =400.00
  4.                 //将bitmap放至数组中,意在bitmap的大小(与实际读取的原文件要大)   
  5.                 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
  6.                 bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
  7.                 byte[] b = baos.toByteArray(); 
  8.                 //将字节换成KB 
  9.                 double mid = b.length/1024
  10.                 //判断bitmap占用空间是否大于允许最大空间  如果大于则压缩 小于则不压缩 
  11.                 if (mid > maxSize) { 
  12.                         //获取bitmap大小 是允许最大大小的多少倍 
  13.                         double i = mid / maxSize; 
  14.                         //开始压缩  此处用到平方根 将宽带和高度压缩掉对应的平方根倍 (1.保持刻度和高度和原bitmap比率一致,压缩后也达到了最大大小占用空间的大小) 
  15.                         bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i), 
  16.                                         bitMap.getHeight() / Math.sqrt(i)); 
  17.                 } 
  18.         } 
  19.  
  20.  
  21.  
  22. /***
  23.          * 图片的缩放方法
  24.          *
  25.          * @param bgimage
  26.          *            :源图片资源
  27.          * @param newWidth
  28.          *            :缩放后宽度
  29.          * @param newHeight
  30.          *            :缩放后高度
  31.          * @return
  32.          */ 
  33.         public static Bitmap zoomImage(Bitmap bgimage, double newWidth, 
  34.                         double newHeight) { 
  35.                 // 获取这个图片的宽和高 
  36.                 float width = bgimage.getWidth(); 
  37.                 float height = bgimage.getHeight(); 
  38.                 // 创建操作图片用的matrix对象 
  39.                 Matrix matrix = new Matrix(); 
  40.                 // 计算宽高缩放率 
  41.                 float scaleWidth = ((float) newWidth) / width; 
  42.                 float scaleHeight = ((float) newHeight) / height; 
  43.                 // 缩放图片动作 
  44.                 matrix.postScale(scaleWidth, scaleHeight); 
  45.                 Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, 
  46.                                 (int) height, matrix, true); 
  47.                 return bitmap; 
  48.         } 
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值