【Android基础】Android图片压缩

在Android中,图片压缩是一个比较重要的概念,因为手机内存有限,而现在的图片的分辨率是越来越高,不进行压缩,内存开销大,同时也会存在OOM的问题;
下面介绍一种Android系统框架自带的压缩方式,能对原图片的宽高进行指定压缩,话不多说,直接上代码【代码注解比较详细,可以直接使用】;
package com.example.imagepresstest01;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

public class MainActivity extends Activity {
	public static final String TAG = "MainActivity";
 public ImageView myiv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 1.获取当前应用最大的“可用”内存;
		int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
		Log.d(TAG, "Max memory is " + maxMemory + "KB");
		// 4.控件显示压缩后的图片
		myiv = (ImageView)findViewById(R.id.myiv);
		myiv.setImageBitmap(
			    decodeSampledBitmapFromResource(getResources(),R.drawable.myimage, 300, 300));

	}

	// 2.获取图片的的宽和高,然后计算出压缩比率;
	public static 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) {
			// 计算出实际宽高和目标宽高的比率
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			// 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
			// 一定都会大于等于目标的宽和高。
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}
	//3.根据比率,将原图片进行压缩,
	public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
	        int reqWidth, int reqHeight) {
		//这里是一个获取图片大小的技巧,将inJustDecodeBounds设置为true,来获取图片大小,
	    final BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    BitmapFactory.decodeResource(res, resId, options);
	    // 调用上面定义的方法计算inSampleSize值
	    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
	    // 将inJustDecodeBounds设置为false,才能进行压缩操作,使用获取到的inSampleSize值再次解析图片
	    options.inJustDecodeBounds = false;
	    return BitmapFactory.decodeResource(res, resId, options);
	}
}
这是图片原来的像素

运行的结果如图所示【300px*300px】:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值