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

前端 未结 3 1647
梦谈多话
梦谈多话 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.

    0 讨论(0)
  • 2020-12-05 16:35

    You can load image as Bitmap. This way its size will be unchanged.

    BitmapFactory.decodeStream(...)
    

    Or you can try BitmapDrawable(InputStream is) constructor. It is deprecated but I guess it should do the job.

    0 讨论(0)
  • 2020-12-05 16:40

    After a long time, I came across the following solution. It works. It retrieves creates bitmap from file at locallink.

    private Drawable getDrawableForStore(String localLink) {
        Bitmap thumbnail = null;
        try {
            File filePath = this.getFileStreamPath(localLink);
            FileInputStream fi = new FileInputStream(filePath);
            thumbnail = BitmapFactory.decodeStream(fi);
        } catch (Exception ex) {
            Log.e("getThumbnail() on internal storage", ex.getMessage());
            return null;
        }
    
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        float scaledDensity = metrics.density;
        int width = thumbnail.getWidth();
        int height = thumbnail.getHeight();
    
        if(scaledDensity<1){
    
            width = (int) (width *scaledDensity);
            height = (int) (height *scaledDensity);
        }else{
            width = (int) (width +width *(scaledDensity-1));
            height = (int) (height +height *(scaledDensity-1));
        }
    
        thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true);
        Drawable d = new BitmapDrawable(getResources(),thumbnail);
    
        return d;
    
    }
    
    0 讨论(0)
提交回复
热议问题