android 图片压缩

/**
     * 简单压缩
     *
     * @param is
     * @return Bitmap
     */
    public static Bitmap setOption(InputStream is) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 10; // width,hight设为原来的十分一
        Bitmap btp = BitmapFactory.decodeStream(is, null, options);
        return btp;
    }

    /**
     * 压缩图片方法
     *
     * @return Bitmap
     * @param context
     * @param file
     */
    public static Bitmap setCompress(Activity context, File file) {

        BitmapFactory.Options opt = new BitmapFactory.Options();
        // 这个isjustdecodebounds很重要
        opt.inJustDecodeBounds = true;
        Bitmap bm = BitmapFactory.decodeFile(file.getPath(), opt);
//        Log.i("tag", "w11=" + bm.getWidth());
//        Log.i("tag", "h11=" + bm.getHeight());

        // 获取到这个图片的原始宽度和高度
        int picWidth = opt.outWidth;
        int picHeight = opt.outHeight;
        // 获取屏的宽度和高度
        WindowManager windowManager = context.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int screenWidth = display.getWidth();
        int screenHeight = display.getHeight();

        // isSampleSize是表示对图片的缩放程度,比如值为2图片的宽度和高度都变为以前的1/2
        opt.inSampleSize = 1;
        // 根据屏的大小和图片大小计算出缩放比例
        if (picWidth > picHeight) {
            if (picWidth > screenWidth)
                opt.inSampleSize = picWidth / screenWidth;
        } else {
            if (picHeight > screenHeight)

                opt.inSampleSize = picHeight / screenHeight;
        }

        // 这次再真正地生成一个有像素的,经过缩放了的bitmap
        opt.inJustDecodeBounds = false;
        bm = BitmapFactory.decodeFile(file.getPath(), opt);

        int w = bm.getWidth();
        int h = bm.getHeight();
        // Log.i("tag", bm.toString());
//        Log.i("tag", "w22=" + w);
//        Log.i("tag", "h22=" + h);

        // 用imageview显示出bitmap
        // im1.setImageBitmap(bm);

        return bm;

    }

转载于:https://my.oschina.net/juna/blog/688145

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值