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 t开发者_高级运维he Android device my app is running on has a density of 1.5 then the following code returns a BitmapDrawable with a width of 320
URL url = new URL("http://www.examples.com/something.png");
Drawable d = Drawable.createFromStream(url.openStream(), "something.png");
Is there a method to force it to be unchanged or specify the scale (ldpi/mdpi/hdpi etC) to return an image from an InputStream?
Edit: Solution from below.
Bitmap b = BitmapFactory.decodeStream(inputStream);
b.setDensity(Bitmap.DENSITY_NONE);
Drawable d = new BitmapDrawable(b);
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.
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.
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;
}
精彩评论