How do you load an image?

edited September 2016 in How To...

I think that my syntax is correct but when i load the image, nothing shows up and then the program says "nullpointerexception" and crashes

Tagged:

Answers

  • It would help if we could see the code you are using.

  • Image needs to be in a subdirectory called 'data'. Check that the name is correct.

  • This is the code

    PImage pepe;

    void setup () { size(720,480);

    }

    void draw() { background(0); pepe = loadImage("pepe.jpg"); image(pepe,100,100); }

    But every time I run it it crashes and the other window that runs the sketch just displays a white screen and my the Mac pinwheel comes up.

  • edited September 2016 Answer ✓

    Do not load your image in draw.

    DO NOT LOAD YOUR IMAGE IN DRAW.

    DO! NOT! LOAD! YOUR! IMAGE! IN! DRAW!

    DO!!! NOT!!! LOAD!!! YOUR!!! IMAGE!!! IN!!! DRAW!!!

    DO NOT LOAD YOUR IMAGE IN DRAW.

    Once more:

    DO NOT LOAD YOUR IMAGE IN DRAW!

  • Answer ✓

    Here is some much better code. Can you see why it's better? (Hint: Where is the image being loaded?)

    PImage pepe;
    
    void setup () {
      size(720,480);
      pepe = loadImage("pepe.jpg");
    }
    
    void draw() {
      background(0);
      image(pepe,100,100);
    }
    

    If this doesn't work, make sure that you have added the image to your sketch's data folder.

  • @TajA, to clarify, running "loadImage" in draw() will attempt to open your image file and load the data 60 times per second. If the image takes longer than 1/60th of a second to load, hilarity ensues -- if you want to build a house and then go inside every day, don't start building a house every day, then demolish what you've built every midnight and start over. Just build it once. Then go inside every day.

    From the loadImage() reference:

    In most cases, load all images in setup() to preload them at the start of the program. Loading images inside draw() will reduce the speed of a program. Images cannot be loaded outside setup() unless they're inside a function that's called after setup() has already run.

Sign In or Register to comment.