nurzain-pradana

Untitled

Jun 7th, 2020
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. public void loadImagefromGallery() {
  2. //create intent to open image application like Gallery, Google Photos
  3. Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  4. //Start intent
  5. startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
  6. }
  7.  
  8. //when image is selected from gallery
  9. @Override
  10. protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
  11. super.onActivityResult(requestCode, resultCode, data);
  12. try {
  13. //when image is picked
  14. if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
  15. //get image from data
  16. Uri selectedImage = data.getData();
  17. String[] filePathColumn = {MediaStore.Images.Media.DATA};
  18.  
  19. //Get the cursor
  20. if (selectedImage != null) {
  21. Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
  22. if (cursor != null) {
  23. cursor.moveToFirst();
  24. int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
  25. imgPath = cursor.getString(columnIndex);
  26. cursor.close();
  27. }
  28. }
  29.  
  30. //set image in imageView
  31. ivRegisterPhoto.setImageBitmap(BitmapFactory.decodeFile(imgPath));
  32.  
  33. //get the image's filename
  34. String[] fileNameSegments = imgPath.split("/");
  35. fileName = fileNameSegments[fileNameSegments.length - 1];
  36. } else {
  37. Toast.makeText(this, "You Haven't picked image", Toast.LENGTH_LONG).show();
  38. }
  39. } catch (Exception e) {
  40. Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment