How to create a Drawable from a stream without resizing it?

前端 未结 3 1652
梦谈多话
梦谈多话 2020-12-05 16:18

If I have the minimum target SDK for my app set to 4 then all calls to Drawable.createFromStream resize images.

e.g. if the source image is 480px wide and the Androi

3条回答
  •  执念已碎
    2020-12-05 16:32

    Loading images from local resource in ImageView Adapter

    I was stuck with OOM error in ion by Koushik Dutta, for as low as 2 images, loading from the resource folder. Even he mentioned it may happen since they are not streams of data. and suggested to load them as InputStream.

    I chucked ion Library since i wanted just 4 images from the local.

    here is the solution with simple ImageView.

    inside the RecyclerViewAdapter/ or any where

     InputStream inputStream = mContext.getResources().openRawResource(R.drawable.your_id);
    
        Bitmap b = BitmapFactory.decodeStream(inputStream);
        b.setDensity(Bitmap.DENSITY_NONE);
        Drawable d = new BitmapDrawable(b);
        holder.mImageView.setImageDrawable(d);
    

    Although Drawable d = new BitmapDrawable(b); is deprecated but, does the job quite well.

    so instead we can directly get drawable from InputStream just by this line..

    Drawable d = Drawable.createFromStream(inputStream,"src");
    

    Hope it helps.

提交回复
热议问题