Android不加载获取网络、本地图片的尺寸

来源:互联网 发布:淘宝小号怎样申请 编辑:程序博客网 时间:2024/06/08 13:24

一、根据网络数据流来获取大小

class GetImageSizeTask extends AsyncTask<Void, Void, Boolean> {        String TAG = this.getClass().getName();        String urlStr = "http://www.3dmgame.com/uploads/allimg/160902/328_160902163518_1.jpg";        int width, height;        @Override        protected Boolean doInBackground(Void... voids) {            boolean result = false;            try {                URL mUrl = new URL(urlStr);                HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();                InputStream is = connection.getInputStream();                BitmapFactory.Options options = new BitmapFactory.Options();                options.inJustDecodeBounds = true;                BitmapFactory.decodeStream(is, null, options);                width = options.outWidth;                height = options.outHeight;                result = true;            }            catch (MalformedURLException e) {                e.printStackTrace();            }            catch (IOException e) {                e.printStackTrace();            }            return result;        }        @Override        protected void onPostExecute(Boolean aBoolean) {            if(aBoolean) {                Log.i(TAG, "width: " + width + "     height: " + height);            }            else {                Log.i(TAG, "获取失败");            }        }    }

二、利用Glide来获取图片大小

    String url = "http://www.3dmgame.com/uploads/allimg/160902/328_160902163518_1.jpg";    Glide.with(this).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {        @Override        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {            Log.i("TAG", "width: " + resource.getWidth() + "     height: " + resource.getHeight());        }    });

三、获取本地图片尺寸

    String src = "/mnt/sdcard/names.jpg";    BitmapFactory.Options options = new BitmapFactory.Options();    options.inJustDecodeBounds = true;    //bitmap.options类为bitmap的裁剪类,通过他可以实现bitmap的裁剪;如果不设置裁剪后的宽高和裁剪比例,返回的bitmap对象将为空,但是这个对象存储了原bitmap的宽高信息,bitmap对象为空不会引发OOM。    Bitmap bitmap = BitmapFactory.decodeFile(src, options);    int width = options.outWidth;    int height = options.outHeight;    Log.i("TAG", "width: " + width + "     height: " + height);
原创粉丝点击