美文网首页
简单的图片二次采样

简单的图片二次采样

作者: 沈溺_16e5 | 来源:发表于2019-03-21 08:26 被阅读0次

    刚开始会出现加载不出控件的情况,获取width和height可能为0,所以放在onWindowFocusChanged方法中

        @Override
        public void onWindowFocusChanged(boolean hasFocus) {
    
            super.onWindowFocusChanged(hasFocus);
    
            // ImageView 的实际大小
            int width = img.getWidth();
            int height = img.getHeight();
            Log.e(TAG, "initView: " + "width:" + width + ",height:" + height);
    
            // 不二次采样bitmap大小
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bb);
            Log.e(TAG, "init: " +"不二次采样bitmap大小: "+bitmap.getAllocationByteCount() );
    
            // 设置为true,加载图片时不会获取到bitmap对象,但是可以拿到图片的宽高
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(getResources(), R.drawable.bb, options);
    
            // 获取图像的宽高值
            int outWidth = options.outWidth;
            int outHeight = options.outHeight;
            Log.e(TAG, "init: " + "outWidth: "+outWidth+",outHeight:"+outHeight);
    
            // 计算宽度比和高度比
            float widthRatio = outWidth * 1.0f / width;
            float heightRatio = outHeight * 1.0f / height;
            Log.e(TAG, "init: " + "widthRatio: "+widthRatio+",heightRatio:"+heightRatio);
    
            // 计算采样率
            float max = Math.max(widthRatio, heightRatio);
            int inSampleSize = (int) Math.ceil(max);
            Log.e(TAG, "init: " + "inSampleSize: "+inSampleSize);
    
            // 设置通过采样率更改压缩图片,加载图片显示
            options.inJustDecodeBounds=false;
            options.inSampleSize = inSampleSize;
    
            // 二次采样bitmap大小
            Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.bb, options);
    
            // 显示压缩后的图片
            img.setImageBitmap(bitmap1);
        }
    

    相关文章

      网友评论

          本文标题:简单的图片二次采样

          本文链接:https://www.haomeiwen.com/subject/zvuwmqtx.html