xxxxxxxxxx
58
let img; // Imagen cargada
let asciiDensity = "@#W$9876543210?!abc;:+=-,._ "; // Caracteres para el arte ASCII
let input, button; // Elementos de carga de imagen
function setup() {
createCanvas(800, 800);
background(0);
noLoop();
// Crear el input para subir una imagen
input = createFileInput(handleFile);
input.position(10, 10);
// Crear un botón para generar el ASCII art
button = createButton("Generar ASCII Art");
button.position(10, 40);
button.mousePressed(() => {
if (img) {
drawAsciiArt();
}
});
}
function handleFile(file) {
if (file.type === "image") {
img = loadImage(file.data, () => {
img.resize(width, height); // Ajustar la imagen al tamaño del canvas
background(0); // Limpiar el fondo
image(img, 0, 0, width, height); // Mostrar la imagen original
});
} else {
console.error("Por favor, sube un archivo de imagen.");
}
}
function drawAsciiArt() {
background(0); // Limpiar el canvas
img.filter(GRAY); // Convertir la imagen a escala de grises
// Dibujar ASCII
let w = width / img.width;
let h = height / img.height;
textFont("monospace");
textSize(6); // Tamaño de los caracteres
fill(255);
noStroke();
for (let y = 0; y < img.height; y++) {
for (let x = 0; x < img.width; x++) {
let pixelColor = img.get(x, y); // Obtener el color del píxel
let brightness = brightness(pixelColor); // Calcular brillo
let charIndex = floor(map(brightness, 0, 255, asciiDensity.length - 1, 0)); // Mapear brillo a índice
let char = asciiDensity[charIndex]; // Obtener carácter correspondiente
text(char, x * w, y * h); // Dibujar el carácter
}
}
}