Swayam
Swayam

Reputation: 16354

How to load an ImageView with a png file without using "setImageBitmap()"?

I do some processing (quality improvement and a bit of resizing) on a Bitmap object and then store it using bitmap.compress() function by giving a file name "myfile.png".

newbitmap = processImage(bitmap);
FileOutputStream fos = context.openFileOutput("myfile.png", Context.MODE_PRIVATE);
newbitmap.compress(CompressFormat.PNG, 100, fos);

Now I want to load this image in an ImageView but I cant use setImageBitmap() to do that. Is there any alternative ?

The reason I cant use setImageBitmap() is that I am using RemoteViews for a widget, and using bitmap method leads to Failed Binder Transaction error when the image is large.

I tried to set image uri using the code below but the image does not load on the ImageView:

RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

File internalFile = context.getFileStreamPath("myfile.png");
Uri internal = Uri.fromFile(internalFile);
rv.setImageViewUri(R.id.widgetImageView, internal);
updateAppWidget(awID, rv);

Thanks for your help!

Upvotes: 6

Views: 2237

Answers (2)

Shubham
Shubham

Reputation: 820

While storing images in internal storage, you have to set the mode to MODE_WORLD_READABLE instead of MODE_PRIVATE. This is because a widget is handled by the home screen process and it cant access your files if you dont set the mode right.

So replace this line:

FileOutputStream fos = context.openFileOutput("myfile.png", Context.MODE_PRIVATE);

with:

FileOutputStream fos = context.openFileOutput("myfile.png", Context.MODE_WORLD_READABLE);

Also, use Uri.parse() and getPath() instead of fromFile(). fromFile() works only on Android 2.2 and above.

Uri internal = Uri.Parse(internalFile.getPath());

Hope this helps!

Upvotes: 2

Leon Lucardie
Leon Lucardie

Reputation: 9730

Using rv.setUri(R.id.widgetImageView, "setImageURI", "file://myfile.png"); instead of rv.setImageViewUri(R.id.widgetImageView, internal); seems to load the image correctly. You might want to give that a try.

If that doesn't work there's still the option to scaling down the image so that you can use the setImageBitmap method. Example:

 public static Bitmap scaleDownBitmap(Bitmap photo, int newHeight, Context context) {

 final float densityMultiplier = context.getResources().getDisplayMetrics().density;        

 int h= (int) (newHeight*densityMultiplier);
 int w= (int) (h * photo.getWidth()/((double) photo.getHeight()));

 photo=Bitmap.createScaledBitmap(photo, w, h, true);

 return photo;
 }

Upvotes: 1

Related Questions