How to get 'get()' working on image created by 'createImg()'?

Hello. I’m currently making a program where I need to get a section of an image and save it to a given variable. The problem is that ‘get()’ only works on p5.Image objects and when I try to use it on an image created by the ‘createImg()’ function, I get a “.get is not a function” error.

Note: the ‘copy()’ function doesn’t do the work for me. I’ve also unsuccessfully tried to make the createImg() image a child of the p5.Image class.

Hi @kkouch,

Welcome to the forum! :wink:

Is there a specific reason you are using createImg() instead of using loadImage()? (Note that you can also use both)

A solution is to draw your image into another canvas and get a portion of it:

function setup() {
  const canvas = createCanvas(500, 500);

  let img = createImg(
    "https://p5js.org/assets/img/asterisk-01.png",
    "the p5 magenta asterisk"
  );

  const offScreenCanvas = createGraphics(img.width, img.height);
  offScreenCanvas.drawingContext.drawImage(img.elt, 0, 0);

  const region = offScreenCanvas.get(0, 0, 50, 50);

  image(region, 0, 0);
}

function draw() {
  noLoop();
}

But you can also have both loadImage and createImage with the preload() function that will wait for the image to download (and you won’t load it twice since it’s cached):

let img, imgDOM;
const imageURL =
  "https://images.pexels.com/photos/14139354/pexels-photo-14139354.jpeg?auto=compress&cs=tinysrgb&w=630&h=375&dpr=2";

function preload() {
  img = loadImage(imageURL);
}

function setup() {
  const canvas = createCanvas(500, 500);

  imgDOM = createImg(imageURL, "web image");

  const region = img.get(0, 0, 50, 50);
  image(region, 0, 0);
}

function draw() {
  noLoop();
}

(CC image from www.pexels.com)

3 Likes

Thank you, I really didn’t think about using a second canvas.

Is there a specific reason you are using createImg() instead of using loadImage()?

Yes, because I’m using createFileInput to load an image from the PC.

EDIT: Turns out createFileInput works with loadImage too! Thank you a lot.

2 Likes