Half Tone p5 Sketch

The drawing machine I’m working on still only can make dots, so I need to create an algorithm that can convert images into dots also known as half toning an image.

This sketch essentially grabs a the brightness at a given increment and assigns it a radius value. This is then used to draw an array of circles with wider circles standing in for brighter pixels. The button on the bottom right starts the process while the button on the bottom left shows the original image. Code below:

var img;
var img;
let button;
let show;
let pixy = [];
let tog = false;
let tog2 = false;
let maxDiam = 10;

function setup() {  createCanvas(640, 480);
  button = createButton("Save Image");
  button.position(width - 100, height - 40);
  button.mousePressed(saveImage);

  show = createButton("Show/Hide Image");
  show.position(25, height - 40);
  show.mousePressed(showImage);

  for (let i = 0; i < height / maxDiam; i += 1){
    pixy[i] = [];  }
}
function draw() {
  noStroke();
  fill(255);
  if (tog == true) {
    image(img, 0,0);
  }
  if (tog == false) {
    background(0);
  }

  if (tog2 == true || tog == false){
    for (let i = 0; i < height / maxDiam; i++){ // noprotect
      for (let j = 0; j < width / maxDiam; j++){ // noprotect
        ellipse(j * maxDiam + maxDiam / 2, i * maxDiam + maxDiam / 2, pixy[i][j], pixy[i][j]);
      }
    }
  }
}
function preload() {
  img = loadImage("assets/image.jpg");
}
function saveImage() {
  let imgPixel = img;
  for (let i = 0; i < height/maxDiam; i++){    // noprotect
    for (let j = 0; j < width/maxDiam; j++){   // noprotect
  let p = img.get(j * maxDiam + maxDiam / 2, i * maxDiam + maxDiam / 2);
      pixy[i][j] = map(int(brightness(p)), 0, 100, 0, maxDiam);
    }
  }
  tog2 = true;
}
function showImage() {
  tog = !tog;
}

Leave a Reply

Your email address will not be published. Required fields are marked *