公司项目中有一个功能,就是用户能够上传图片到我们的服务器中,图片可以是用户本地图片,也可以是用户拍摄的照片。这些图片不受我们控制,有些照片可能很大,比如手机相机拍摄的,大小都是几兆的,用户直接上传这么大的图片肯定是不行的,网速慢的话上传很耗时,而且在非WIFI情况下,肯定要消耗用户大量的流量。
别忘了添加读写SD卡的权限,不然会报错。
所以,我们需要把用户选择的图片先压缩,然后再上传。下面将介绍一个高效的图片压缩方法,基本上能够把几兆的图片压缩到几百KB甚至100KB以下,而且不失真,以SD卡下/big_images目录中的一个图片为例,这个图片是手机拍摄的,大小为3.1M。
一、判断图片大小
上传图片时,先判断图片的大小,如果图片大小于1M的话,就不需要压缩了,可以直接上传;当图片大于1M的话在就行压缩。
- // SD卡根目录路径
- sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
- // 需要判断大小的图片路径
- String bigImage = sdCardPath + "/test_images/big.jpg";
- // 获取指定文件的指定单位的大小 param1:文件路径 param2:获取大小的类型 1为B、2为KB、3为MB、4为GB
- double bigSize = FileSizeUtil.getFileOrFilesSize(bigImage, 3);
- tv_big.setText("图片压缩前的大小为:" + bigSize + "MB");
二、压缩图片
- // 当图片大于1M时,才进行压缩
- String smallImage;
- if (bigSize > 1){
- smallImage = compress(bigImage);
- } else {
- smallImage = bigImage;
- }
- double smallSize = FileSizeUtil.getFileOrFilesSize(smallImage, 2);
- tv_small.setText("图片压缩后的大小为:" + smallSize + "KB");
compress方法:
- private String compress(String path) {
- if (path != null) {
- try {
- File file = new File(path);
- Bitmap bm = PictureUtil.getSmallBitmap(path);
- String sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
- String dirPath = sdCardPath + "/test_images/";
- FileOutputStream fos = new FileOutputStream(new File( dirPath,"small.jpg"));
- bm.compress(Bitmap.CompressFormat.JPEG, 40, fos);
- String newPath = dirPath + "small.jpg";
- return newPath;
- } catch (Exception e) {
- }
- }
- return path;
- }
其中需要用到两个工具类:
1.FileSizeUtil.java
- public class FileSizeUtil {
- public static final int SIZETYPE_B = 1;// 获取文件大小单位为B的double值
- public static final int SIZETYPE_KB = 2;// 获取文件大小单位为KB的double值
- public static final int SIZETYPE_MB = 3;// 获取文件大小单位为MB的double值
- public static final int SIZETYPE_GB = 4;// 获取文件大小单位为GB的double值
- /**
- * 获取文件指定文件的指定单位的大小
- * @param filePath 文件路径
- * @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
- * @return double值的大小
- */
- public static double getFileOrFilesSize(String filePath, int sizeType) {
- File file = new File(filePath);
- long blockSize = 0;
- try {
- if (file.isDirectory()) {
- blockSize = getFileSizes(file);
- } else {
- blockSize = getFileSize(file);
- }
- } catch (Exception e) {
- e.printStackTrace();
- Log.e("获取文件大小", "获取失败!");
- }
- return FormetFileSize(blockSize, sizeType);
- }
- /**
- * 调用此方法自动计算指定文件或指定文件夹的大小
- * @param filePath 文件路径
- * @return 计算好的带B、KB、MB、GB的字符串
- */
- public static String getAutoFileOrFilesSize(String filePath) {
- File file = new File(filePath);
- long blockSize = 0;
- try {
- if (file.isDirectory()) {
- blockSize = getFileSizes(file);
- } else {
- blockSize = getFileSize(file);
- }
- } catch (Exception e) {
- e.printStackTrace();
- Log.e("获取文件大小", "获取失败!");
- }
- return FormetFileSize(blockSize);
- }
- /**
- * 获取指定文件大小
- */
- private static long getFileSize(File file) throws Exception {
- long size = 0;
- if (file.exists()) {
- FileInputStream fis = null;
- fis = new FileInputStream(file);
- size = fis.available();
- } else {
- file.createNewFile();
- Log.e("获取文件大小", "文件不存在!");
- }
- return size;
- }
- /**
- * 获取指定文件夹
- */
- private static long getFileSizes(File f) throws Exception {
- long size = 0;
- File flist[] = f.listFiles();
- for (int i = 0; i < flist.length; i++) {
- if (flist[i].isDirectory()) {
- size = size + getFileSizes(flist[i]);
- } else {
- size = size + getFileSize(flist[i]);
- }
- }
- return size;
- }
- /**
- * 转换文件大小
- */
- private static String FormetFileSize(long fileS) {
- DecimalFormat df = new DecimalFormat("#.00");
- String fileSizeString = "";
- String wrongSize = "0B";
- if (fileS == 0) {
- return wrongSize;
- }
- if (fileS < 1024) {
- fileSizeString = df.format((double) fileS) + "B";
- } else if (fileS < 1048576) {
- fileSizeString = df.format((double) fileS / 1024) + "KB";
- } else if (fileS < 1073741824) {
- fileSizeString = df.format((double) fileS / 1048576) + "MB";
- } else {
- fileSizeString = df.format((double) fileS / 1073741824) + "GB";
- }
- return fileSizeString;
- }
- /**
- * 转换文件大小,指定转换的类型
- */
- private static double FormetFileSize(long fileS, int sizeType) {
- DecimalFormat df = new DecimalFormat("#.00");
- double fileSizeLong = 0;
- switch (sizeType) {
- case SIZETYPE_B:
- fileSizeLong = Double.valueOf(df.format((double) fileS));
- break;
- case SIZETYPE_KB:
- fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
- break;
- case SIZETYPE_MB:
- fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
- break;
- case SIZETYPE_GB:
- fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824));
- break;
- default:
- break;
- }
- return fileSizeLong;
- }
- }
2.PictureUtil.java
- public class PictureUtil {
- /**
- * 把bitmap转换成String
- */
- public static String bitmapToString(String filePath) {
- Bitmap bm = getSmallBitmap(filePath);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
- byte[] b = baos.toByteArray();
- return Base64.encodeToString(b, Base64.DEFAULT);
- }
- /**
- * 计算图片的缩放值
- */
- public static int calculateInSampleSize(BitmapFactory.Options options,
- int reqWidth, int reqHeight) {
- // Raw height and width of image
- final int height = options.outHeight;
- final int width = options.outWidth;
- int inSampleSize = 1;
- if (height > reqHeight || width > reqWidth) {
- // Calculate ratios of height and width to requested height and
- // width
- final int heightRatio = Math.round((float) height / (float) reqHeight);
- final int widthRatio = Math.round((float) width / (float) reqWidth);
- // Choose the smallest ratio as inSampleSize value, this will
- // guarantee
- // a final image with both dimensions larger than or equal to the
- // requested height and width.
- inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
- }
- return inSampleSize;
- }
- /**
- * 根据路径获得突破并压缩返回bitmap用于显示
- */
- public static Bitmap getSmallBitmap(String filePath) {
- final BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeFile(filePath, options);
- // Calculate inSampleSize
- options.inSampleSize = calculateInSampleSize(options, 480, 800);
- // Decode bitmap with inSampleSize set
- options.inJustDecodeBounds = false;
- return BitmapFactory.decodeFile(filePath, options);
- }
- /**
- * 根据路径删除图片
- */
- public static void deleteTempFile(String path) {
- File file = new File(path);
- if (file.exists()) {
- file.delete();
- }
- }
- /**
- * 添加到图库
- */
- public static void galleryAddPic(Context context, String path) {
- Intent mediaScanIntent = new Intent(
- Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
- File f = new File(path);
- Uri contentUri = Uri.fromFile(f);
- mediaScanIntent.setData(contentUri);
- context.sendBroadcast(mediaScanIntent);
- }
- /**
- * 获取保存图片的目录
- */
- public static File getAlbumDir() {
- File dir = new File(
- Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
- getAlbumName());
- if (!dir.exists()) {
- dir.mkdirs();
- }
- return dir;
- }
- /**
- * 获取保存 隐患检查的图片文件夹名称
- */
- public static String getAlbumName() {
- return "sheguantong";
- }
- }
别忘了添加读写SD卡的权限,不然会报错。
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>