压缩图片加载的简单方式

当需要加载的图片过大时,该图片将占用大量可用内存,从而造成卡顿,所以当我们用软件展示图片时需要对图片进行适当的压缩,具体做法如下:
工具类:

public class BitmapUtils {
    /**
     * 计算压缩比例
     * 
     * @param options
     *            封装图片的实际的高度,宽度
     * @param reqWidth
     *            需要的宽度
     * @param reqHeight
     *            需求的高度
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // read height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        // 通过此变量记录压缩比例(1表示不压缩)
        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;
    }

    /** 压缩图片 */
    public static Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true
        // to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//此值为true表示只读图片边界信息
        // read dimension (height,width)
        BitmapFactory.decodeFile(path, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }
}

然后再MainActivity中用如下方式调用

public class MainActivity extends Activity {
    private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView=(ImageView) findViewById(R.id.imageView1);
    }
    public void onClick(View v){
        File file=new File("/mnt/sdcard/ql.jpg");
        //imageView.setImageURI(Uri.fromFile(file));
        Bitmap bitmap=BitmapUtils.
        decodeSampledBitmapFromResource(
        file.getPath(),200,200);
        imageView.setImageBitmap(bitmap);
    }



}

你可能感兴趣的:(工具)