xxxxxxxxxx
PImage img;
PImage newimg;
final string fileName = "Vsauce.png"; //select file here
final string chars = {"#", "%", "@", "$", "0", "=", "=", "."};
//origional: {"#", "%", "@", "$", "0", "=", "-", ":", "."};
final int blur = -1; //-1 to stay as default, 0 for none, 1 for one pixel, 2 for 2 pixels, etc
final float shrinkFactor = 8; //default : 2 [higher value = lower resolution image, 0.5 = twice the resolution]
final int shrinkSize;
string[] ascii;
int stage;
int i = 0;
int j = 0;
int ni = 0;
int nj = 0;
int ai = 0;
int aj = 0;
stringAscii = "";
void setup() {
size(700, 700);
frameRate(60);
stage = 2;
fill(255);
img = requestImage(fileName); //upload any image
//Make sure the string here ^^ matches the name of your file
}
void initVar() {
shrinkSize = int(img.width / shrinkFactor);
newimg = createImage(shrinkSize, shrinkSize);
if (blur == -1) {
blur = ceil(img.width / shrinkSize);
}
}
void draw() {
background(0);
if (img.width == 0) { //STEP 1: wait until image finishes loading
textSize(25);
textAlign(CENTER, CENTER);
text("Loading...", width / 2, 3 * height / 4);
textSize(12);
textAlign(LEFT);
return;
}
if (stage == 2) {
initVar(); //STEP 2: initiate variables
stage++;
}
if (stage == 3) {
render(newimg.width * newimg.height / 120); //STEP 3: 'render' the image used for converting to ascii
}
image(newimg, 0, 0, width, height);
// show the PImage on screen
if (stage == 4) { //STEP 4: print ascii art into console
renderAscii(newimg.width * newimg.height / 120);
}
textSize(11);
fill(255);
text("fps: " + int(frameRate), 5, 15);
}
void render(int iters) {
newimg.loadPixels();
img.loadPixels();
for (int iter = 0; iter < iters; iter++) {
ni = int(i * img.width / newimg.width);
nj = int(j * img.height / newimg.height);
int a = 0; //sum
int l = 0; //length
for (int n = -blur; n <= blur; n++) {
for (int m = -blur; m <= blur; m++) {
if (ni + n < 0 || ni + n >= img.width || nj + m < 0 || nj + m >= img.height) {
continue;
}
a += int(brightness(img.pixels[ni + n + (nj + m) * img.width]));
l++;
}
}
a = a / l;
newimg.pixels[i + j * newimg.width] = color(a);
if (i < newimg.width) {
i++;
} else {
i = 0;
j++;
}
if (j >= newimg.height) {
stage++;
newimg.updatePixels();
return;
}
}
newimg.updatePixels();
}
void renderAscii(int nnn) {
newimg.loadPixels();
for (int iterate = 0; iterate < nnn; iterate++) {
if (aj >= newimg.height) {
fill(255);
textSize(12);
text("Done! Check console for output.", 5, 30);
return;
}
stringAscii = stringAscii + " " + chars[int(chars.length * brightness(newimg.pixels[ai + aj * newimg.width]) / 256)];
ai++;
if (ai >= newimg.width) {
ai = 0;
aj++;
println(stringAscii);
stringAscii = "";
if (aj >= newimg.height) {
return;
}
}
}
fill(255);
textSize(12);
text("Printing ASCII to console: " + stringAscii, 5, 30);
}