Select an Existing Image

We can create an Intent that allows the user to select an existing image using the built-in capabilities and display that image in our sketch.

Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,␣ android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

Here is an example:

final int CHOOSE_PICTURE = 0;

String imageFilePath;
PImage selectedImage;

void setup() {
  
}

void draw() {
  if (selectedImage != null) {
    image(selectedImage,0,0,width,height); 
  }
}

void mousePressed() {
  android.content.Intent choosePictureIntent = new android.content.Intent(android.content.Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  startActivityForResult(choosePictureIntent, CHOOSE_PICTURE);
}

protected void onActivityResult(int requestCode, int resultCode, android.content.Intent intent) { 
  super.onActivityResult(requestCode, resultCode, intent);
  if (resultCode == RESULT_OK) {
    
    android.net.Uri imageFileUri = intent.getData();
    // This Uri is a "content://" style intent which Processing can't use directly.  We need to query the MediaStore to get the file path
    //println(imageFileUri.toString());
    // content://media/external/images/media/9397
    
    String[] columns = { android.provider.MediaStore.Images.Media.DATA }; // The file path
    android.database.Cursor cursor = managedQuery(imageFileUri, columns, null, null, null);
    if (cursor.moveToFirst()) { 
      imageFilePath = cursor.getString(cursor.getColumnIndexOrThrow(android.provider.MediaStore.Images.Media.DATA));
      println(imageFilePath);
      selectedImage = loadImage(imageFilePath);
    }
  }
}