首页 > 代码库 > 每日总结 - 图片压缩

每日总结 - 图片压缩

利用android系统压缩方式进行图片压缩,代码:

 1 private String path = "/sdcard/img.jpg"; 2 File f = new File(path); 3 Bitmap bm = PictureUtil.getSmallBitmap(this,path); 4 FileOutputStream fos; 5     try { 6         fos = new FileOutputStream(new File("/sdcard/", "small_" + f.getName())); 7         bm.compress(Bitmap.CompressFormat.JPEG, 90, fos); 8     } catch (FileNotFoundException e) { 9         e.printStackTrace();10         }        

getSmallBitmap方法是根据路径获得图片并压缩返回bitmap用于显示。

 1     /** 2      * 计算图片的缩放值 3      *  4      * @param options 5      * @param reqWidth 6      * @param reqHeight 7      * @return 8      */ 9     public static int calculateInSampleSize(BitmapFactory.Options options,10             int reqWidth, int reqHeight) {11         // Raw height and width of image12         final int height = options.outHeight;13         final int width = options.outWidth;14         int inSampleSize = 1;15 16         if (height > reqHeight || width > reqWidth) {17 18             // Calculate ratios of height and width to requested height and19             // width20             final int heightRatio = Math.round((float) height21                     / (float) reqHeight);22             final int widthRatio = Math.round((float) width / (float) reqWidth);23 24             // Choose the smallest ratio as inSampleSize value, this will25             // guarantee26             // a final image with both dimensions larger than or equal to the27             // requested height and width.28             inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;29         }30 31         return inSampleSize;32     }33 34     35 36     37     /**38      * 根据路径获得图片并压缩返回bitmap用于显示39      * 40      * @param imagesrc41      * @return42      */43     public static Bitmap getSmallBitmap(Context context ,String filePath) {44         final BitmapFactory.Options options = new BitmapFactory.Options();45         options.inJustDecodeBounds = true;46         BitmapFactory.decodeFile(filePath, options);47 48         DisplayMetrics dm = context.getResources().getDisplayMetrics();49         50         // Calculate inSampleSize51         options.inSampleSize = calculateInSampleSize(options, dm.widthPixels, dm.heightPixels);52 53         // Decode bitmap with inSampleSize set54         options.inJustDecodeBounds = false;55 56         return BitmapFactory.decodeFile(filePath, options);57     }

 

每日总结 - 图片压缩