Project-09: ASCii Portrait

had a lot of fun w dis one

sketch
// Zoe Lin (ID: youlin)
// Section B

//please give it a couple seconds to load!
//press the mouse to invert the colors!
var density = '@Ñ#W$0985321!?=+-;:,._ ';
var r, g, b;
var img;

function preload() {
  img = loadImage("https://i.imgur.com/GBXXDnf.png"); //load image
}

function setup() {
  createCanvas(350, 450);
  //frameRate(10);
  textAlign(CENTER, CENTER); //ensures ascii text aligns with pixels
  noStroke();
}

function draw() {
  img.loadPixels(); //loads each individual pixel of img
  background(0);

  //var denShuffle = shuffle(density);
  var newWidth = width/img.width;
  var newHeight = height/img.height;
  for (var i = 0; i < img.width; i++) {
    for (var j = 0; j < img.height; j++) {
      var index = (i+j*img.width) * 4; //sets index to match image pixel
      r = img.pixels[index]; g = img.pixels[index+1]; b = img.pixels[index+2];
      var average = (r+g+b) / 3; //finds average rgb index
      textSize(newWidth);
      fill(255);

      //maps index of letter to image pixels
      var letterdex = floor(map(average,0,255,density.length,0));
      //draws ascii letters
      text(density.charAt(letterdex), i*newWidth, j*newHeight);
      
    }
  }  
}

//note: mousePressed also takes a few seconds to load!
function mousePressed() { //inverts colors when mouse is pressed
  density = density.split('').reverse().join(''); //reverses density string
}

Leave a Reply