A. Rad
A. Rad

Reputation: 43

Loading thousands of images to use within p5.js

How would I go about loading thousands of images in p5.js? The only good way for images to actually load is within the preload() function, but I am making a program that needs to load 3498 images, and loading 10.9 GB of images, assumingly into RAM, with preload(), won't work. The reason I want to do this is to manipulate the frames by merging them and rotating them and then exporting them.

let frameNum = 3498;
let overlapNum = 10;
let overlapAngle;

function setup() {
    createCanvas(1080, 1080);
    overlapAngle = QUARTER_PI * 0.08;
}

function draw() {
    background(0);
    push();
    translate(width / 2, width / 2);
    tint(255, 255 / overlapNum);
    let imgSize = width / sin(QUARTER_PI);
    let rotAmount = frameCount / 120.0 * TWO_PI;
    for (i = 0; i < overlapNum; i++) {
        let imgNum = ((frameCount * 10) + i + 3496) % (frameNum) + 1;
        push();
        rotate(i / float(overlapNum) * overlapAngle + rotAmount);
        let img = loadImage("Input/frame-" + str(imgNum).padStart(5, "0") + ".png");
        image(img, -imgSize / 2, -imgSize / 2, imgSize, imgSize);
        print("Input/frame-" + str(imgNum).padStart(5, "0") + ".png");
        print(imgSize);
        pop();
    }
    pop();
}

The result of this is just a blank canvas. Nothing loads. I tried loading an image into preload() and that works.

I hope I didn't word my question badly. Thank you.

Upvotes: 2

Views: 1420

Answers (1)

Jacob Stuligross
Jacob Stuligross

Reputation: 1479

In your comment, you have the right idea. The loadImage() function can take up to 3 parameters. If you make a function for displaying the image as you want it, and pass the function name as the second parameter of loadImage(), that function will be called when the image has loaded (with the loaded image as the input). Something like this might work:

function setup() {
  //... your setup stuff
  frameRate(0.1);
}

function draw() {
  //...
  for (...) {
    loadImage('file path', dispImage);
  }
}

function dispImage(image_to_display) {
  this.img = image_to_display;
  //... do whatever to display the image
}

I put the frameRate() command in because I don't think that the for loop will wait until one image is displayed to load the next image, so in order for this to work, you need the frame rate to be slow enough to allow a bunch of images to load between frames.

I didn't test this out, so I may have made mistakes or misunderstood something.

Upvotes: 1

Related Questions