I'm trying to set the image from a specific filepath ON THE PHONE. The filepath is to the photo on the phone. the filepath could look like this
/storage/emulated/0/Pictures/picture.jpg
Here is the code.
Bitmap image = null;
//trying to set the image from filepath
try {
image = BitmapFactory.decodeStream((InputStream) new URL(filepath).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (image == null) {
//This becomes true because the image is not set
Toast.makeText(getApplicationContext(),"image == null",Toast.LENGTH_LONG).show();
}
In the end the image is not set.
If you’re working with an Android application, this source code works as a way to load an image from a file: Bitmap bitmap = BitmapFactory.decodeFile (pathToPicture); The Bitmap and BitmapFactory classes are located in the android.graphics package: import android.graphics.Bitmap; import android.graphics.BitmapFactory;
The Bitmap and BitmapFactory classes are located in the android.graphics package: Assuming that your pathToPicture is correct, you can then add this bitmap image to an ImageView like this: As shown, the setImageBitmap method is another key to this solution.
2. How To Get The Real File Path From Android URI. At some time, only save the image URI in the android app is not enough, because the image URI may be changed, or the image URI is not changed but its related image may be removed. In this case, we need to save the URI-related images in the android app folder.
If your Android app wants to access other app created files, you should get the file from its ContentProvider with a content URI. The ContentProvider URI is not a real android file path URI ( file:///storage/41B7-12F1/DCIM/Camera/IMG_20180211_095139.jpg ), it is a content provider style URI ( content://media/external/images/media/1302716 ).
Use This Method to get Bitmap from Filepath
public Bitmap getBitmap(String path) {
Bitmap bitmap=null;
try {
File f= new File(path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
image.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap ;
}
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