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

I do some processing (quality improvement and a little resizing) on ​​the Bitmap object, and then save it using the bitmap.compress() function, specifying the 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 into ImageView , but I cannot use setImageBitmap() for this. Is there an alternative?

The reason I cannot use setImageBitmap() is because I use RemoteViews for the widget, and using the bitmap method results in a Failed Binder Transaction error when the image is large.

I tried installing the uri image using the code below, but the image does not load on 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!

+6
source share
2 answers

When storing images in the internal storage, you should set the mode to MODE_WORLD_READABLE instead of MODE_PRIVATE . This is due to the fact that the widget is processed by the home screen process, and it cannot access your files if you have not configured the mode in the right direction.

So replace this line:

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

from:

 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 higher.

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

Hope this helps!

+2
source

Using rv.setUri(R.id.widgetImageView, "setImageURI", "file://myfile.png"); instead of rv.setImageViewUri(R.id.widgetImageView, internal); seems to be loading the image correctly. You can try to try.

If this does not work, there is still the option of scaling 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; } 
+1
source

Source: https://habr.com/ru/post/922642/


All Articles