how to get image from gallery in android 10 and above
- Create a Directory for data to be stored in Android/data/package name by:
private void createDir() {
String timeStamp = utils.currentTimeStamp();
File storageDir = getExternalFilesDir(null);
File image;
try {
image = File.createTempFile(timeStamp, “.png”, storageDir);
Log.i(“SANJAY “, “createDir: “ + image.getPath());
} catch (IOException e) {
e.printStackTrace();
Log.i(“SANJAY “, “createDir: “ + e.getMessage());
}
}
2. now call the gallery intent:
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType(“image/*”);
startActivityForResult(intent, 100);
3. In onActivityResult():
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 100) {
Uri mediaUri = data.getData();
//display the image
try {
InputStream inputStream = getBaseContext().getContentResolver().openInputStream(mediaUri);
Bitmap bm = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] byteArray = stream.toByteArray();
bind.photo.setImageBitmap(bm);
//Log.i(“SANJAY “, “onActivityResult: “ + saveBitMap(this, bm));
uri = Uri.fromFile(saveBitMap(this, bm));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
4. the get the Uri from File using this method:
private File saveBitMap(Context context, Bitmap Final_bitmap) {
File pictureFileDir = new File(Environment.getExternalStorageDirectory()
+ “/Android/data/”
+ getApplicationContext().getPackageName()
+ “/”/*Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), “”*/);
if (!pictureFileDir.exists()) {
boolean isDirectoryCreated = pictureFileDir.mkdirs();
if (!isDirectoryCreated)
Log.i(“SANJAY “, “Can’t create directory to save the image”);
return null;
}
String filename = pictureFileDir.getPath() + File.separator + System.currentTimeMillis() + “.jpg”;
File pictureFile = new File(filename);
try {
pictureFile.createNewFile();
FileOutputStream oStream = new FileOutputStream(pictureFile);
Final_bitmap.compress(Bitmap.CompressFormat.PNG, 18, oStream);
oStream.flush();
oStream.close();
Log.i(“SANJAY “, “saveBitMap :: Save Image Successfully..”);
} catch (IOException e) {
e.printStackTrace();
Log.i(“SANJAY”, “There was an issue saving the image.”);
Log.i(“SANJAY”, “Error :: “ + e.getLocalizedMessage());
}
return pictureFile;
}