Android图片压缩,先进行尺寸压缩,再质量压缩

// 获取压缩后的图片地址
// 进行尺寸压缩之后再进行质量压缩
public static String getCompressedPath(Context context, String path) {
	try {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;                                       // 获取图片的宽高,图片并没有加载进内存
		BitmapFactory.decodeFile(path, options);
		
		int originWidth = options.outWidth;
		int originHeight = options.outHeight;
		// 目标尺寸的宽高根据具体情况来定
		float targetHeight = 1024f;
		float targetWidth = 1024f;
		int rate = 1;                                                             // rate=1表示不缩放
		if (originWidth >= originHeight && originWidth > targetWidth) {           // 如果宽度大的话根据宽度固定大小缩放
			rate = (int) (options.outWidth / targetWidth);
		} else if (originWidth < originHeight && originHeight > targetHeight) {   // 如果高度高的话根据宽度固定大小缩放
				rate = (int) (options.outHeight / targetHeight);
		}
		if (rate <= 0) rate = 1;

		options.inSampleSize = rate;                                              // 设置缩放比例
		options.inJustDecodeBounds = false;                                       // 这里一定要将其设置回false,因为之前我们将其设置成了true

		Bitmap bitmap = BitmapFactory.decodeFile(path, options);

		String name = String.valueOf(System.currentTimeMillis());
		File uploadImageDir = new File(getUploadImageDir(context));
		File uploadImageFile = new File(uploadImageDir + "/" + name + ".jpg");    // 压缩后的图片位置
			
		if (!uploadImageDir.exists()) {
			uploadImageDir.mkdirs();
		} else {
			if (uploadImageFile.exists()) {
				uploadImageFile.delete();
			}
		}
			
		try {
			FileOutputStream out = new FileOutputStream(uploadImageFile);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);                  // 进行质量压缩
			out.flush();
			out.close();
			bitmap.recycle();                                                      // 回收bitmap,节省内存
			return uploadImageFile.getAbsolutePath();
		} catch (Exception e) {
			e.printStackTrace();
		}
			
	} catch (Exception e) {
		e.printStackTrace();
	} catch (OutOfMemoryError e) {
		e.printStackTrace();
	}
	return null;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值