Mask image with Text

Hello everyone!

So, quick question, I want to mask a image with a string of text from the code, but I can’t seem to figure out how to mask with text… I’m trying to achieve something like this:

When I search about this I only find the mask() function with images…
Can anyone help me?

Thanks in advance!

1 Like

You can draw the text to an an off-screen graphics buffer, then use that buffer as a guide to govern which pixels in the original photograph to leave as they are, and which ones to make black.

let img;
let pg;
function preload() {
  img = loadImage("box_turtle.jpg");
}

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

function draw() {
  img.loadPixels();
  // create a p5.Graphics: offscreen graphics buffer
  pg = createGraphics(width, height);
  pg.textAlign(CENTER, CENTER);
  pg.textSize(120);
  pg.textStyle(BOLD);
  pg.background(0);
  // draw text to buffer in white
  pg.fill(255);
  pg.text("Eastern\nBox\nTurtle", width / 2, height / 2);
  pg.loadPixels();
  // use the buffer as a guide for altering the image
  for (var i = 0; i < img.pixels.length; i += 4) {
    // if buffer pixel is not white (red is not 255) blacken the image pixel 
    if (pg.pixels[i] != 255) {
      img.pixels[i] = 0;
      img.pixels[i+1] = 0;
      img.pixels[i+2] = 0;
    }
  }
  img.updatePixels();
  image(img, 0, 0);
}

eastern_box_turtle

Source of image: Female Eastern Box Turtle #4 by Sandy Richard

Edited on January 17, 2020 to make a slight revision to the code and to provide a link to the image.

2 Likes

Thank you!! This is exactly what I was looking for! I completely forgot about using createGraphics(), thank you again :blush:

1 Like

You are quite welcome, @anarts_3, - and welcome to the Processing Forums!

Note that using variables to set the size of the canvas, as follows, is not recommended, but it did work, and does offer a convenience.

  createCanvas(img.width, img.height);

To avoid potential trouble, you could hard code the width and the height with constants instead.

1 Like