Android使用BitMap压缩图片(高效加载大图)Code+详解
示例代码:
package com.example.p0063508.testbitmap;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
private ImageView imageView = null ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imgview);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(),R.mipmap.img,options);
Log.i("main1","压缩前的高"+options.outWidth);
Log.i("main1","压缩前的宽"+options.outHeight);
Log.i("main1","图片类型"+ options.outMimeType);
//进行图片压缩
Bitmap bitmap = decodeSampledBitmapFromResource(getResources(),R.mipmap.img,100,100);
imageView.setImageBitmap(bitmap);
Log.i("main1","压缩后的宽"+bitmap.getWidth());
Log.i("main1","压缩后的高"+bitmap.getHeight());
}
/**
* 计算压缩的比例
* @param options
* @param reqWidth 压缩最小的宽度
* @param reqHeight 压缩最小的宽度
* @return
*/
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) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
/**
* 压缩图片
* @param res
* @param resId
* @param reqWidth 压缩最小的宽度
* @param reqHeight 压缩最小的宽度
* @return
*/
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId