Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void loadImagefromGallery() {
- //create intent to open image application like Gallery, Google Photos
- Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
- //Start intent
- startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
- }
- //when image is selected from gallery
- @Override
- protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- try {
- //when image is picked
- if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
- //get image from data
- Uri selectedImage = data.getData();
- String[] filePathColumn = {MediaStore.Images.Media.DATA};
- //Get the cursor
- if (selectedImage != null) {
- Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
- if (cursor != null) {
- cursor.moveToFirst();
- int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
- imgPath = cursor.getString(columnIndex);
- cursor.close();
- }
- }
- //set image in imageView
- ivRegisterPhoto.setImageBitmap(BitmapFactory.decodeFile(imgPath));
- //get the image's filename
- String[] fileNameSegments = imgPath.split("/");
- fileName = fileNameSegments[fileNameSegments.length - 1];
- } else {
- Toast.makeText(this, "You Haven't picked image", Toast.LENGTH_LONG).show();
- }
- } catch (Exception e) {
- Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment