Drag and dropping an image into a running sketch and reading its info

I want to create a sketch where you can drag and drop an image into the window, which then sets the window size to that of the image and then draws the image in the center of the window.

I already found how to dynamically change the window size, but I am stumped as to how to do the drag and drop part. While searching online I found a library from 2010 that seemingly does this, but I am not sure whether it would work with the current version of processing.

here is an example using the Drop library that you can download directly within
Processing (Menu Sketch | import library)

It’s directly taken from the lib’s examples and slightly modified, room for improvement for example where the window gets resized…



/**
 * loading an image from the web or the harddisk with sDrop.
 */

import drop.*;

SDrop drop;

PImage myPImage;

// ------------------------------------------------------------------------------------------

void setup() {
  size(400, 400);
  // frameRate(30);
  windowResizable(true);
  drop = new SDrop(this);
}

void draw() {
  // flickering background to see the framerate interference
  // when loading an image. there should be none since the images
  // are loaded in their own thread.
  background(255);

  if (myPImage != null) {
    image(myPImage, 10, 10);
    windowResize(myPImage.width, myPImage.height);
  }
}

void keyPressed() {
  if (myPImage != null) {
    println(myPImage.width + " :  " + myPImage.height);
  }
}

// ------------------------------------------------------------------------------------------

void dropEvent(DropEvent theDropEvent) {
  println("");
  println("isFile()\t"+theDropEvent.isFile());
  println("isImage()\t"+theDropEvent.isImage());
  println("isURL()\t"+theDropEvent.isURL());

  if (  theDropEvent.isFile()  ) {
    println("file()\t"+theDropEvent.file());
    File f1 =   theDropEvent.file();
    println("  " + f1.getAbsolutePath());
  }

  // if the dropped object is an image, then
  // load the image into our PImage.
  if (theDropEvent.isImage()) {
    println("### loading image ...");
    myPImage = theDropEvent.loadImage();
  }
}

1 Like