在使用相机拍摄照片时 原图在1到3m左右 但是在上传使用时 文件较大很耗时 在服务器访问时获取较慢 所以对上传图片进行了压缩 以消耗图片质量的情况下减小图片 降低了清晰度 直接上方法
对于取到的相册或拍照图片路径
oldPath
进行处理//图片压缩 300k左右 private String getThumbUploadPath(String oldPath, int bitmapMaxWidth) throws Exception { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(oldPath, options); int height = options.outHeight; int width = options.outWidth; int reqHeight = 0; int reqWidth = bitmapMaxWidth; reqHeight = (reqWidth * height) / width; // 在内存中创建bitmap对象,这个对象按照缩放大小创建的 options.inSampleSize = calculateInSampleSize(options, bitmapMaxWidth, reqHeight); options.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeFile(oldPath, options); Bitmap bm = compressImage(Bitmap.createScaledBitmap(bitmap, bitmapMaxWidth, reqHeight, false)); // saveMyBitmap(bm); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return saveMyBitmap(bm); } private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { if (width > height) { inSampleSize = Math.round((float) height / (float) reqHeight); } else { inSampleSize = Math.round((float) width / (float) reqWidth); } } return inSampleSize; } private Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 options -= 10;// 每次都减少10 baos.reset();// 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片 return bitmap; } /** * 保存Bitmap到sd卡 * * @param mBitmap * @return */ public String saveMyBitmap(Bitmap mBitmap) { if (!checkSDcardValid() || !createDir()) { return ""; } String currentPhotoName = System.currentTimeMillis() + ".jpg"; File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/zpay/"); File out = new File(dir, currentPhotoName); try { out.createNewFile(); } catch (IOException e) { e.printStackTrace(); } FileOutputStream fOut = null; try { fOut = new FileOutputStream(out); mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); } catch (FileNotFoundException e) { e.printStackTrace(); } try { fOut.flush(); fOut.close(); } catch (IOException e) { e.printStackTrace(); } Log.d(TAG, "压缩图路径:" + out.getAbsolutePath()); return out.getAbsolutePath(); }
经过处理后保存到新路径 图片大小在300k左右 减小上传压力
String uploadBufferpath = getThumbUploadPath(path, 480);