[关闭]
@Tyhj 2017-02-24T09:24:05.000000Z 字数 1429 阅读 1417

Android图片压缩

Android


原文:https://www.zybuluo.com/Tyhj/note/666195
Android中,图片展示的时候可以用各种框架,图片工具来很好的展示。但是涉及到图片上传的时候,比如上传头像什么的,我们就可以先将图片压缩一下再上传。

  1. //计算图片的缩放值
  2. public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
  3. final int height = options.outHeight;
  4. final int width = options.outWidth;
  5. int inSampleSize = 1;
  6. if (height > reqHeight || width > reqWidth) {
  7. final int heightRatio = Math.round((float) height/ (float) reqHeight);
  8. final int widthRatio = Math.round((float) width / (float) reqWidth);
  9. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
  10. }
  11. return inSampleSize;
  12. }
  1. //图片压缩
  2. public static void ImgCompress(String filePath,File newFile,int IMAGE_SIZE) {
  3. //图片质量百分比
  4. int imageMg=100;
  5. final BitmapFactory.Options options = new BitmapFactory.Options();
  6. options.inJustDecodeBounds = true;
  7. BitmapFactory.decodeFile(filePath, options);
  8. //规定要压缩图片的分辨率
  9. options.inSampleSize = calculateInSampleSize(options,1080,1920);
  10. options.inJustDecodeBounds = false;
  11. Bitmap bitmap= BitmapFactory.decodeFile(filePath, options);
  12. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  13. bitmap.compress(Bitmap.CompressFormat.JPEG, imageMg, baos);
  14. //如果文件大于100KB就进行质量压缩,每次压缩比例增加百分之五
  15. while (baos.toByteArray().length / 1024 > IMAGE_SIZE&&imageMg>60){
  16. baos.reset();
  17. imageMg-=5;
  18. bitmap.compress(Bitmap.CompressFormat.JPEG, imageMg, baos);
  19. }
  20. //然后输出到指定的文件中
  21. FileOutputStream fos = null;
  22. try {
  23. fos = new FileOutputStream(newFile);
  24. fos.write(baos.toByteArray());
  25. fos.flush();
  26. fos.close();
  27. baos.close();
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. }
  31. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注