How to remove whitespace from p5.js rendered image?

Member

by larissa , in category: Javascript , 8 months ago

How to remove whitespace from p5.js rendered image?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 8 months ago

@larissa 

To remove whitespace from a p5.js rendered image, you can use the get function to determine the boundaries of the image and then create a new image with the non-whitespace pixels. Here is an example code snippet that shows how to remove whitespace from a p5.js rendered image:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
let img;

function preload() {
  img = loadImage('image.jpg');
}

function setup() {
  createCanvas(img.width, img.height);

  loadPixels();
  let minX = img.width;
  let minY = img.height;
  let maxX = 0;
  let maxY = 0;

  for (let x = 0; x < img.width; x++) {
    for (let y = 0; y < img.height; y++) {
      let loc = (x + y * img.width) * 4;
      let r = pixels[loc];
      let g = pixels[loc + 1];
      let b = pixels[loc + 2];
      let a = pixels[loc + 3];

      if (r !== 255 || g !== 255 || b !== 255 || a !== 255) {
        minX = min(minX, x);
        minY = min(minY, y);
        maxX = max(maxX, x);
        maxY = max(maxY, y);
      }
    }
  }

  let newWidth = maxX - minX + 1;
  let newHeight = maxY - minY + 1;
  let newImg = createImage(newWidth, newHeight);

  newImg.copy(img, minX, minY, newWidth, newHeight, 0, 0, newWidth, newHeight);
  image(newImg, 0, 0);

  updatePixels();
}


This code snippet first loads an image and creates a canvas with the same dimensions as the image. It then loops through all the pixels in the image to determine the boundaries of the non-whitespace pixels. It creates a new image with those boundaries and displays it on the canvas. This will effectively remove any whitespace from the image.

Related Threads:

How to rotate image in p5.js?
How to fill shapes with image in p5.js and matter.js?
How to save image to specific directory in p5.js?
How to draw only segment of whole image with p5.js?
How to find colors of an image with p5.js?
How to load image and make it as background in p5.js?