公司项目中有一个功能,就是用户能够上传图片到我们的服务器中,图片可以是用户本地图片,也可以是用户拍摄的照片。这些图片不受我们控制,有些照片可能很大,比如手机相机拍摄的,大小都是几兆的,用户直接上传这么大的图片肯定是不行的,网速慢的话上传很耗时,而且在非WIFI情况下,肯定要消耗用户大量的流量。
所以,我们需要把用户选择的图片先压缩,然后再上传。下面将介绍一个高效的图片压缩方法,基本上能够把几兆的图片压缩到几百KB甚至100KB以下,而且不失真,以SD卡下/big_images目录中的一个图片为例,这个图片是手机拍摄的,大小为3.1M。
一、判断图片大小
上传图片时,先判断图片的大小,如果图片大小于1M的话,就不需要压缩了,可以直接上传;当图片大于1M的话在就行压缩。
1. // SD卡根目录路径
2. sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
3. // 需要判断大小的图片路径
4. String bigImage = sdCardPath + "/test_images/big.jpg";
5.
6. // 获取指定文件的指定单位的大小 param1:文件路径 param2:获取大小的类型 1为B、2为KB、3为MB、4为GB
7. double bigSize = FileSizeUtil.getFileOrFilesSize(bigImage, 3);
8. tv_big.setText("图片压缩前的大小为:" + bigSize + "MB");
二、压缩图片
1. // 当图片大于1M时,才进行压缩
2. String smallImage;
3. if (bigSize > 1){
4. smallImage = compress(bigImage);
5. } else {
6. smallImage = bigImage;
7. }
8.
9. double smallSize = FileSizeUtil.getFileOrFilesSize(smallImage, 2);
10. tv_small.setText("图片压缩后的大小为:" + smallSize + "KB");
compress方法:
1. private String compress(String path) {
2. if (path != null) {
3. try {
4. File file = new File(path);
5. Bitmap bm = PictureUtil.getSmallBitmap(path);
6. String sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
7. "/test_images/";
8.
9. new FileOutputStream(new File( dirPath,"small.jpg"));
10.
11. 40, fos);
12.
13. "small.jpg";
14.
15. return newPath;
16. catch (Exception e) {
17.
18. }
19. }
20. return path;
21. }
其中需要用到两个工具类:
1.FileSizeUtil.java
1. public class FileSizeUtil {
2. public static final int SIZETYPE_B = 1;// 获取文件大小单位为B的double值
3. public static final int SIZETYPE_KB = 2;// 获取文件大小单位为KB的double值
4. public static final int SIZETYPE_MB = 3;// 获取文件大小单位为MB的double值
5. public static final int SIZETYPE_GB = 4;// 获取文件大小单位为GB的double值
6.
7. /**
8. * 获取文件指定文件的指定单位的大小
9. * @param filePath 文件路径
10. * @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
11. * @return double值的大小
12. */
13. public static double getFileOrFilesSize(String filePath, int sizeType) {
14. new File(filePath);
15. long blockSize = 0;
16. try {
17. if (file.isDirectory()) {
18. blockSize = getFileSizes(file);
19. else {
20. blockSize = getFileSize(file);
21. }
22. catch (Exception e) {
23. e.printStackTrace();
24. "获取文件大小", "获取失败!");
25. }
26. return FormetFileSize(blockSize, sizeType);
27. }
28.
29. /**
30. * 调用此方法自动计算指定文件或指定文件夹的大小
31. * @param filePath 文件路径
32. * @return 计算好的带B、KB、MB、GB的字符串
33. */
34. public static String getAutoFileOrFilesSize(String filePath) {
35. new File(filePath);
36. long blockSize = 0;
37. try {
38. if (file.isDirectory()) {
39. blockSize = getFileSizes(file);
40. else {
41. blockSize = getFileSize(file);
42. }
43. catch (Exception e) {
44. e.printStackTrace();
45. "获取文件大小", "获取失败!");
46. }
47. return FormetFileSize(blockSize);
48. }
49.
50. /**
51. * 获取指定文件大小
52. */
53. private static long getFileSize(File file) throws Exception {
54. long size = 0;
55. if (file.exists()) {
56. null;
57. new FileInputStream(file);
58. size = fis.available();
59. else {
60. file.createNewFile();
61. "获取文件大小", "文件不存在!");
62. }
63. return size;
64. }
65.
66. /**
67. * 获取指定文件夹
68. */
69. private static long getFileSizes(File f) throws Exception {
70. long size = 0;
71. File flist[] = f.listFiles();
72. for (int i = 0; i < flist.length; i++) {
73. if (flist[i].isDirectory()) {
74. size = size + getFileSizes(flist[i]);
75. else {
76. size = size + getFileSize(flist[i]);
77. }
78. }
79. return size;
80. }
81.
82. /**
83. * 转换文件大小
84. */
85. private static String FormetFileSize(long fileS) {
86. new DecimalFormat("#.00");
87. "";
88. "0B";
89. if (fileS == 0) {
90. return wrongSize;
91. }
92. if (fileS < 1024) {
93. double) fileS) + "B";
94. else if (fileS < 1048576) {
95. double) fileS / 1024) + "KB";
96. else if (fileS < 1073741824) {
97. double) fileS / 1048576) + "MB";
98. else {
99. double) fileS / 1073741824) + "GB";
100. }
101. return fileSizeString;
102. }
103.
104. /**
105. * 转换文件大小,指定转换的类型
106. */
107. private static double FormetFileSize(long fileS, int sizeType) {
108. new DecimalFormat("#.00");
109. double fileSizeLong = 0;
110. switch (sizeType) {
111. case SIZETYPE_B:
112. double) fileS));
113. break;
114. case SIZETYPE_KB:
115. double) fileS / 1024));
116. break;
117. case SIZETYPE_MB:
118. double) fileS / 1048576));
119. break;
120. case SIZETYPE_GB:
121. double) fileS / 1073741824));
122. break;
123. default:
124. break;
125. }
126. return fileSizeLong;
127. }
128. }
2.PictureUtil.java
1. public class PictureUtil {
2. /**
3. * 把bitmap转换成String
4. */
5. public static String bitmapToString(String filePath) {
6. Bitmap bm = getSmallBitmap(filePath);
7. new ByteArrayOutputStream();
8. 40, baos);
9. byte[] b = baos.toByteArray();
10. return Base64.encodeToString(b, Base64.DEFAULT);
11. }
12.
13. /**
14. * 计算图片的缩放值
15. */
16. public static int calculateInSampleSize(BitmapFactory.Options options,
17. int reqWidth, int reqHeight) {
18. // Raw height and width of image
19. final int height = options.outHeight;
20. final int width = options.outWidth;
21. int inSampleSize = 1;
22.
23. if (height > reqHeight || width > reqWidth) {
24. // Calculate ratios of height and width to requested height and
25. // width
26. final int heightRatio = Math.round((float) height / (float) reqHeight);
27. final int widthRatio = Math.round((float) width / (float) reqWidth);
28. // Choose the smallest ratio as inSampleSize value, this will
29. // guarantee
30. // a final image with both dimensions larger than or equal to the
31. // requested height and width.
32. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
33. }
34. return inSampleSize;
35. }
36.
37. /**
38. * 根据路径获得突破并压缩返回bitmap用于显示
39. */
40. public static Bitmap getSmallBitmap(String filePath) {
41. final BitmapFactory.Options options = new BitmapFactory.Options();
42. true;
43. BitmapFactory.decodeFile(filePath, options);
44. // Calculate inSampleSize
45. 480, 800);
46. // Decode bitmap with inSampleSize set
47. false;
48. return BitmapFactory.decodeFile(filePath, options);
49. }
50.
51. /**
52. * 根据路径删除图片
53. */
54. public static void deleteTempFile(String path) {
55. new File(path);
56. if (file.exists()) {
57. file.delete();
58. }
59. }
60.
61. /**
62. * 添加到图库
63. */
64. public static void galleryAddPic(Context context, String path) {
65. new Intent(
66. Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
67. new File(path);
68. Uri contentUri = Uri.fromFile(f);
69. mediaScanIntent.setData(contentUri);
70. context.sendBroadcast(mediaScanIntent);
71. }
72.
73. /**
74. * 获取保存图片的目录
75. */
76. public static File getAlbumDir() {
77. new File(
78. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
79. getAlbumName());
80. if (!dir.exists()) {
81. dir.mkdirs();
82. }
83. return dir;
84. }
85.
86. /**
87. * 获取保存 隐患检查的图片文件夹名称
88. */
89. public static String getAlbumName() {
90. return "sheguantong";
91. }
92. }
别忘了添加读写SD卡的权限,不然会报错。
1. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>