xxxxxxxxxx
80
// Image to ASCII
// The Coding Train / Daniel Shiffman
// https://thecodingtrain.com/CodingChallenges/166-ascii-image.html
// https://youtu.be/55iwMYv8tGI
// ASCII video: https://editor.p5js.org/codingtrain/sketches/KTVfEcpWx
// ASCII image canvas: https://editor.p5js.org/codingtrain/sketches/r4ApYWpH_
// ASCII image DOM: https://editor.p5js.org/codingtrain/sketches/ytK7J7d5j
// ASCII image source text: https://editor.p5js.org/codingtrain/sketches/LNBpdYQHP
// ASCII image weather API: https://editor.p5js.org/codingtrain/sketches/DhdqcoWn4
//ASCII String *arranged in high to low density characters
const density = 'Ñ@#W$9876543210?!abc;:+=-,._ ';
let gloria;
function preload() {
img = loadImage("square.jpg");
}
function setup() {
cnv=createCanvas(1080,1080);
}
function draw() {
background(0);
// To draw image directly without using a variable use line below
// Turn it off when don't need direct reference to image in preview
//image(img, x, y, [width], [height])
//Pixel Ratio (to grab pixel ratio of image to canvas)
let w = width / img.width;
let h = height / img.height;
//load pixel array
img.loadPixels();
for (let i = 0; i < img.width; i++) {
for (let j = 0; j < img.height; j++) {
//column+row*imgWidth*4(R,G,B,A) = red value, +1 = blue, +2 = green
const pixelIndex = (i + j * img.width) * 4;
//every pixel has a (r,g,b,alpha) = (0, 1, 2, 3)
const r = img.pixels[pixelIndex + 0];
const g = img.pixels[pixelIndex + 1];
const b = img.pixels[pixelIndex + 2];
//brightness value
const avg = (r + g + b)/3;
//Pixel elements (draw as square, or circle, or whatever)
noStroke();
fill(255);
//square(i * w, j * h, w);
const len = density.length;
//Take the brightness value (avg), with the range between 0-255 and map it to the density length. Use floor to get whole numbers
const charIndex = floor(map(avg,0,255,0,len));
//text size takes up full width of pixel
textSize(w);
//aligning individual text to center of each pixel
textAlign(CENTER,CENTER);
//w*0.5 & h*0.5 is to shift the letters down to make it at the center of the square
//The charAt() method of String values returns a new string consisting of the single UTF-16 code unit at the given index.
text(density.charAt(charIndex), i * w + w * 0.5, j * h + h * 0.5);
}
}
}
function keyTyped() {
if (key === 's') {
saveCanvas(cnv, 'myCanvas', 'png');
}
}