压缩图片加载的简单方式

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

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);
    }



}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值