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!
ImageView imgView = new ImageView(this); imgView. setBackgroundResource(R. drawable. img1);
For adding an image from Android Studio, Drag the ImageView widget to the activity area of the application, a pop-up dialogue box will open choose from the wide range of drawable resources and click “OK“.
Displays image resources, for example Bitmap or Drawable resources. ImageView is also commonly used to apply tints to an image and handle image scaling.
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!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With