Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android get image to Bitmap from filepath

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.

like image 964
Edvard Åkerberg Avatar asked Aug 19 '15 06:08

Edvard Åkerberg


People also ask

How do I load an image from a file in Android?

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;

How to add a bitmap image to an imageview in Android?

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.

How to get the real file path from Android Uri?

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.

How do I access other app created files in Android?

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


1 Answers

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 ;
}
like image 114
AmniX Avatar answered Oct 06 '22 00:10

AmniX