How to set processing to automatically detect an image size and set it as a background?

edited September 2016 in Questions about Code

From my understanding, setting a background image in processing requires the size of the window to match the dimension of the image.

PImage img = loadImage("background.jpg"); //a 100x100 background image.

However, since size() does not take in variables, how are we suppose to define a background with variable dimensions?

I have tested with the surface.setSize() function but it does not see to work.


PImage img = loadImage("background.jpg"); //a 100x100 background image.


  • edited May 2018 Answer ✓
     * Sized to PImage (v1.2)
     * by GoToLoop (2016-Sep-01)
     * how-to-set-processing-to-automatically-detect-
     * an-image-size-and-set-it-as-a-background#Item_1
    static final String RENDERER = JAVA2D; // JAVA2D, FX2D, P2D, P3D, OPENGL
    static final String HTTPS = "https://", SITE = "";
    static final String FOLDER = "img/", FILE = "processing3-logo", EXT = ".png";
    static final String PATH = HTTPS + SITE + FOLDER + FILE + EXT;
    PImage bg;
    void settings() {
      bg = loadImage(PATH);
      size(bg.width, bg.height, RENDERER);
    void draw() {
  • edited September 2016

    It works! But doesn't the setting function gets called first? Is it due to delay that the setup function is able to read the size()?

  • edited September 2016

    Yes, settings() is called even before setup(). Also needed for size() using variables as its arguments:

    I'm still using Processing v. 3.1.2. And so statement while (bg.width <= 1) delay(100); isn't needed here.

    However, for newer versions, loadImage() is asynchronous by default, and doesn't block!
    It means it can reach statement size(bg.width, bg.height); before the image is loaded & ready!

    That's why I have that delay(); so it awaits width get bigger than 1. Meaning it's ready! ;;)

  • edited September 2016

    On 2nd thought, I guess it is save() & saveFrame() function which are async, not loadImage()! b-(
    Please disregard my explanation before. :-\". Gonna remove the delay() too, not needed! :P

Sign In or Register to comment.