码迷,mamicode.com
首页 > 其他好文 > 详细

每日总结 - 图片压缩

时间:2014-10-09 23:46:53      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   color   io   os   ar   for   sp   

利用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 image
12         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 and
19             // width
20             final int heightRatio = Math.round((float) height
21                     / (float) reqHeight);
22             final int widthRatio = Math.round((float) width / (float) reqWidth);
23 
24             // Choose the smallest ratio as inSampleSize value, this will
25             // guarantee
26             // a final image with both dimensions larger than or equal to the
27             // 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 imagesrc
41      * @return
42      */
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 inSampleSize
51         options.inSampleSize = calculateInSampleSize(options, dm.widthPixels, dm.heightPixels);
52 
53         // Decode bitmap with inSampleSize set
54         options.inJustDecodeBounds = false;
55 
56         return BitmapFactory.decodeFile(filePath, options);
57     }

 

每日总结 - 图片压缩

标签:android   style   blog   color   io   os   ar   for   sp   

原文地址:http://www.cnblogs.com/dongye/p/4014631.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!