Last active
January 9, 2020 10:28
-
-
Save bunjix/7bcf36633e11f787215e to your computer and use it in GitHub Desktop.
Pick an image on Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static final int PICK_PHOTO_FOR_AVATAR = 0; | |
public void pickImage() { | |
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); | |
intent.setType("image/*"); | |
startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR); | |
} | |
@Override | |
public void onActivityResult(int requestCode, int resultCode, Intent data) { | |
super.onActivityResult(requestCode, resultCode, data); | |
if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) { | |
if (data == null) { | |
//Display an error | |
return; | |
} | |
InputStream inputStream = context.getContentResolver().openInputStream(data.getData()); | |
//Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better:
try {
InputStream inputStream = getContext().getContentResolver().openInputStream(data.getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}