Sigueme en Facebook Sigueme en Twitter Sigueme en Instagram Sigueme en Youtube
JC Mouse Bolivia
Index / Java / Java / Proyectos / Proyecto Ascii Art (metodo de Black/white)

Proyecto Ascii Art (metodo de Black/white)

Autor jc mouse martes, junio 28, 2011

El Ascii Art o Arte Ascii, consiste en realizar dibujos con los caracteres ASCII (Código Americano Estándar de Intercambio de Información), y en la actualidad su uso ya es bastante conocido sobre todo en logos de compañias, blogs, foros y redes sociales como facebook utilizados como adornos.

Existen varias formas de realizar este Ascii-Art, por ejemplo:

  • Ascii Art de imagenes en Blanco y Negro
  • Acii Art de imagenes en escala de grises
  • Acii Art de los bordes de una imagen

Empezaremos por el algoritmo más sencillo, que es el Ascii Art de una imagen en blanco y negro.

¿Como funciona?

Dada una imagen en blanco y negro, se van tomando 4 pixeles de 2×2 y se van comparando de acuerdo a un patron previamente definido (Imagen 1), se toman los caracteres ASCII que se asemejen más a la forma que tienen los 4 pixeles extraidos, esto para que la imagen una vez formada, sea lo mas posible fiel a la original.
(Imagen 1)
Los pixeles se iran leyendo fila por fila, saltandose una linea de pixeles, esto para que la imagen resultante no se vea demasiado alargada, las columnas se leen de 2 en 2. La iamgen resultante, dependera tambien del tipo de caracter con el que se imprima, debe escogerse un caracter lo mas cuadrado posible, por ejemplo «Lucida Console».

Cada 4 pixeles leidos, corresponden a un caracter ascii y estos seran unidos a una cadena de texto, cuando se llegue al final de una columna, debe agregarse un «salto de carro» (\n) y continuarse con la siguiente hilera.

La siguiente clase i2ascii.java, resume toda la explicacion anterior.El constrcutor de la clase, lee una imagen en disco y la asigna a una clase de tipo BufferedImage, ademas la convierte en una imagen en blanco/negro utilizando un metodo que se vio en un post anterior (Imagen en blanco y Negro en Java), el metodo encargado de transformar esa imagen a Ascii-Art es ConvertToAscii() el cual devuelve en un String la imagen ya procesada. 

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
 * @web http://jc-mouse.blogspot.com/
 * @author Mouse
 */
public class i2ascii {
    private int r,g,b;
    private Color color;
    private int umbral = 127;
    private int negro = -16777216;
    private int blanco = -1;
    private String ascii = "";
    // los caracteres por los que se reemplazan los pixeles    
    //                             0   1   2   3   4    5   6   7   8   9  10  11  12  13  14     15=\
    private String[] caracter =  {"`","'","°",",",".","\"","_","[","]","J","7","P","L","8","/","" + (char) 92};

    private BufferedImage foto;

    public i2ascii(){
        try {
            //se carga una foto
            foto = ImageIO.read(getClass().getResource("jcmouse.jpg"));
            //foto = ImageIO.read(getClass().getResource("jcmouse.jpg"));
            //se convierte la foto en blanco y negro
            foto = set_Blanco_y_Negro_con_Umbral(foto);

        } catch (IOException ex) {
            Logger.getLogger(i2ascii.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String ConvertToAscii(){
        BufferedImage f = foto;

        int x = f.getWidth();
        int y = f.getHeight();

        //se recorre la matriz de la imagen fila x fila de tres en tres
        for(int j=0;j<y ;j=j+3 ){
          //se recorre la matriz de la imagen col x col de dos en dos
          for(int i=0;i<x;i=i+2 ){

              if( (i < (x-1)) && (j < (y-1)) ){
              //__ 0
              //__
              if( f.getRGB(i, j)==blanco && f.getRGB(i+1, j)==blanco &&
                  f.getRGB(i, j+1)==blanco && f.getRGB(i+1, j+1)==blanco ){
                  ascii = ascii + caracter[0];
                  continue;
              }
              //_X 1
              //__
              if( f.getRGB(i, j)==blanco && f.getRGB(i+1, j)==negro &&
                  f.getRGB(i, j+1)==blanco && f.getRGB(i+1, j+1)==blanco ){
                  ascii = ascii + caracter[1];
                  continue;
              }
              //X_ 2
              //__
              if( f.getRGB(i, j)==negro && f.getRGB(i+1, j)==blanco &&
                  f.getRGB(i, j+1)==blanco && f.getRGB(i+1, j+1)==blanco ){
                    ascii = ascii + caracter[2];
                    continue;
              }
              //__ 3
              //X_
              if( f.getRGB(i, j)==blanco && f.getRGB(i+1, j)==blanco &&
                  f.getRGB(i, j+1)==negro && f.getRGB(i+1, j+1)==blanco ){
                    ascii = ascii + caracter[3];
                    continue;
              }
              //__ 4
              //_X
              if( f.getRGB(i, j)==blanco && f.getRGB(i+1, j)==blanco &&
                  f.getRGB(i, j+1)==blanco && f.getRGB(i+1, j+1)==negro ){
                    ascii = ascii + caracter[4];
                    continue;
              }
              //XX 5
              //__
              if( f.getRGB(i, j)==negro && f.getRGB(i+1, j)==negro &&
                  f.getRGB(i, j+1)==blanco && f.getRGB(i+1, j+1)==blanco ){
                    ascii = ascii + caracter[5];
                    continue;
              }
              //__ 6
              //XX
              if( f.getRGB(i, j)==blanco && f.getRGB(i+1, j)==blanco &&
                  f.getRGB(i, j+1)==negro && f.getRGB(i+1, j+1)==negro ){
                    ascii = ascii + caracter[6];
                    continue;
              }
              //X_ 7
              //X_
              if( f.getRGB(i, j)==negro && f.getRGB(i+1, j)==blanco &&
                  f.getRGB(i, j+1)==negro && f.getRGB(i+1, j+1)==blanco ){
                    ascii = ascii + caracter[7];
                    continue;
              }
              //_X 8
              //_X
              if( f.getRGB(i, j)==blanco && f.getRGB(i+1, j)==negro &&
                  f.getRGB(i, j+1)==blanco && f.getRGB(i+1, j+1)==negro ){
                  ascii = ascii + caracter[8];
                  continue;
              }
              //_X 9
              //XX
              if( f.getRGB(i, j)==blanco && f.getRGB(i+1, j)==negro &&
                  f.getRGB(i, j+1)==negro && f.getRGB(i+1, j+1)==negro ){
                  ascii = ascii + caracter[9];
                  continue;
              }
              //XX 10
              //_X
              if( f.getRGB(i, j)==negro && f.getRGB(i+1, j)==negro &&
                  f.getRGB(i, j+1)==blanco && f.getRGB(i+1, j+1)==negro ){
                  ascii = ascii + caracter[10];
                  continue;
              }
              //XX 11
              //X_
              if( f.getRGB(i, j)==negro && f.getRGB(i+1, j)==negro &&
                  f.getRGB(i, j+1)==negro && f.getRGB(i+1, j+1)==blanco ){
                  ascii = ascii + caracter[11];
                  continue;
              }
              //X_ 12
              //XX
              if( f.getRGB(i, j)==negro && f.getRGB(i+1, j)==blanco &&
                  f.getRGB(i, j+1)==negro && f.getRGB(i+1, j+1)==negro ){
                  ascii = ascii + caracter[12];
                  continue;
              }
              //XX 13
              //XX
              if( f.getRGB(i, j)==negro && f.getRGB(i+1, j)==negro &&
                  f.getRGB(i, j+1)==negro && f.getRGB(i+1, j+1)==negro ){
                  ascii = ascii + caracter[13];
                  continue;
              }

              //_X 14
              //X_
              if( f.getRGB(i, j)==blanco && f.getRGB(i+1, j)==negro &&
                  f.getRGB(i, j+1)==negro && f.getRGB(i+1, j+1)==blanco ){
                  ascii = ascii + caracter[14];
                  continue;
              }

              //X_ 15
              //_X
              if( f.getRGB(i, j)==negro && f.getRGB(i+1, j)==blanco &&
                  f.getRGB(i, j+1)==blanco && f.getRGB(i+1, j+1)==negro ){
                  ascii = ascii + caracter[15];
                  continue;
              }
            }// fin si
          }
          //se concatena la fila resultante y se añade un salto de linea
          ascii = ascii + "\n";
        }        
        //se retorna la imagen transformada en ASCII
        return ascii;
    }

    //Metodo dado una imagen, la convierte en imagen en blanco y negro
    private  BufferedImage set_Blanco_y_Negro_con_Umbral(BufferedImage f){
        BufferedImage bn = new BufferedImage(f.getWidth(),f.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
        //se traspasan los colores Pixel a Pixel
        for(int i=0;i<f.getWidth();i++){
          for(int j=0;j<f.getHeight();j++){
               color = new Color(f.getRGB(i, j));
               //se extraen los valores RGB
                r = color.getRed();
                g = color.getGreen();
                b = color.getBlue();
                //dependiendo del valor del umbral, se van separando los
                // valores RGB a 0 y 255
                r =(r>umbral)? 255: 0;
                g =(g>umbral)? 255: 0;
                b =(b>umbral)? 255: 0;
                bn.setRGB(i, j, new Color(r,g,b).getRGB());
          }
        }
        return bn;
    }

}

Implementar esta clase en una interfaz, es sencilla asi que no creo que sea necesario mostrar como se hace esto. Al ser este un algoritmo simple y utlizar imagenes en blanco y negro, las imagenes resultantes, tambien seran sencillas, es por eso que es mucho mejor utilizar esta tecnica Blanco/Negro en imagenes simples como logotipos o letras.

``````````````````````````````````````````````````````````_______888888_____````````````````````````
``````````````````````````````````````````````````__888888888888888888888888888888__````````````````
````````````````````````````````````````````__8888888888888888888888888888888888888888``````````````
````````````````````````````````````````_888888888888888888888888888888888888888888888``````````````
````````````````````````````````````_J88888888888888888888888888888888888888888888888[``````````````
`````````````````````````````````_888888888888888888888888888888888888888888888888888[``````````````
``````````````````````````````_88888888888888888888888""""````````````""""88888888888°``````````````
```````````````````````````.J888888888888888888P"`````````````````````````````""88888```````````````
`````````````````````````_8888888888888888P"``````````````````````````````````````"88```````````````
```````````````````````J88888888888888P"````````````````````````````88L_,```````````````````````````
`````````````````````J8888888888888"````````````````````````````````88888888__``````````````````````
```````````````````J888888888888"```````````````````````````````````888888888888_,``````````````````
`````````````````J88888888888"``````````````````````````````````````888888888888888L````````````````
```````````````.8888888888"`````````````````````````````````````````88888888888888888L,`````````````
`````````````.888888888P°```````````````````````````````````````````88888888888888888888,```````````
````````````J88888888P````````````````````````````````````````````````"""7888888888888888L``````````
``````````.88888888P````````````````.___J88888888888888L___``````````````````'"888888888888,````````
`````````.8888888P``````````````_J8888""````````````````'"8888L_`````````````````"8888888888,```````
````````]8888888°````````````_888"```][``````````````````8[``'"888,````````````````'788888888[``````
```````J888888P````````````J88°``````888````````````````88P``````"88,`````````````````78888888[`````
``````J888888°````````````.8°`````````8`````````````````'8`````````]8``````````````````'8888888[````
`````J888888°`````````````]8```````.888,````````````````.888,``````]8````````````````````7888888,```
````]888888```````````````]8``````]P.8888,````````````.8888`7,`````]8`````````````````````7888888```
```.88888P````````````````]8[`````8`]88888[``````````]88888[][`````]8[`````````````````````]88888[``
```88888P``````````````````8[`````8`]888888``````````888888[`8`````]8```````````````````````]88888``
``]88888```````````````````8[`````8`]888888``````````888888°][`````]8````````````````````````78888[`
``88888````````````````````8[`````][`888888`````````]888888`J[`````]8`````````````````````````88888`
`]8888°````````````````````8[``````'8_`'"88``````````88"°._8°``````J8`````````````````````````]8888`
`8888P`````````````````````8L`````````""88"``````````788""`````````8P``````````````````````````8888[
]8888``````````````````````]8,``````````````__````_,``````````````.8[``````````````````````````]888[
]888[```````````````````````"8888_,````````'88[``88P`````````._J88P°```````````````````````````]8888
J888°```````````````````````````'"88°```````'8```'P````````"88"`````````````````````````````````8888
8888`````````````````````````````]8`````````````````````````'8[`````````````````````````````````8888
888[``````````````````````.J888_`'8L```J[``````.,``````J[```88`.J888L```````````````````````````8888
888[`````````````````````.88°`'"[`'888888``][``][``8[``88888P`]8"°`'8[``````````````````````````888[
888[`````````````````````]8°````[```'"``8``]L``][``8```8``"```8`````8[`````````````````````````]888[
888[``````````````````````8,```]````````8[``8``][``8``]8``````][````8L,````````````````````````]888`
888[`````````````````````J8L```"88_,````][``7``][``8``JP```_88P°````'788,``````````````````````8888`
]888```````````````````.88°```````'"8L_`]8888L_JLJJ8J88L_88"```````````78[````````````````````]888[`
]888```````````````````]8`````.,``````'"888P"78888""888P°````````_8`````8P````````````````````8888``
`888[```````````````````8L,```/'78_,``````"78L,``_88"°```````_J8"°'L``.JP````````````````````J888[``
`7888````````````````````'"88"`````"88_,``````"7P"```````.J8P°``````"8P°````````````````````]8888```
`]888[````````````````````````````````'"88_``````````._88"`````````````````````````````````.8888[```
``8888,````````````````````````````````_88"``````````'"8_,````````````````````````````````.8888P````
``]8888```````````````````___```````_8P"``````.J8L,``````'78_`````JP8L_``````````````````.88888`````
```8888L````````````````J8°``[``._8"``````._88P°`'"88L,``````"7L,][````7L```````````````.88888°`````
```'8888L``````````````8P````]JP"``````_88P"`````````'788_,``````"°`````8[`````````````J88888°``````
````]8888L`````````````8[``````````_J88"`````````````````"788_,```````.J8°````````````J88888°```````
`````788888,```````````88L,````.J88P°```````__``````````````'"88L,```]8P````````````J888888°````````
``````788888,```````````"88[````8```````````""``````````````````P````]8```````````.8888888``````````
```````788888L````````````88````],``````````88``J888L``````````][````.8`````````.J888888P```````````
````````7888888L``````````]88__88```````````88`]8[`""```````````8L_`.J8```````.J8888888°````````````
`````````]8888888L`````````7888"````````````88`]8,`.,````````````"8888°`````.J8888888P``````````````
``````````'88888888L````````````````````````88`'88_88`````````````````````J88888888P````````````````
````````````"888888888_````````````````````.88`````````````````````````_888888888P``````````````````
``````````````78888888888_````````````````]88[`````````````````````_J8888888888"````````````````````
````````````````7888888888888_,```````````````````````````````._888888888888P°``````````````````````
``````````````````'788888888888888L__,````````````````.___888888888888888P°`````````````````````````
`````````````````````"888888888888888888888888888888888888888888888888"`````````````````````````````
````````````````````````'"888888888888888888888888888888888888888P"`````````````````````````````````
`````````````````````````````""88888888888888888888888888888""``````````````````````````````````````
```````````````````````````````````"""78888888888888P"""````````````````````````````````````````````

Su uso tambien es valido en imagenes complejas como fotografias, aunque el resultado puede variar.

Codigo fuente del proyecto hecho en netbeans 6.9
Click para descargar

Tags

Si te ha gustado podrías compartirlo o dejar un comentario. ¡Muchas gracias!
Autor: JC Mouse

Yo soy yo :) JC Mouse, Soy orgullosamente boliviano soy fundador y CEO de la web jc-Mouse.net uno de las pocas web en emprendimiento y tecnología en Bolivia.

Toda la información que encuentres en este sitio es y sera completamente gratis siempre, puedes copiar, descargar y re-publicar si así lo deseas en otros blogs o sitios web, solo te pido a cambio que dejes una referencia a esta web. Esto nos ayuda a crecer y seguir aportando. Bye

Enjoy! :)

También Te Podría Interesar

Animación de JProgressBar con hilos

Animación de JProgressBar con hilos

Si nuestra aplicación tiene que llevar a cabo un cierto trabajo que no sabemos cuanto durará y que a la vez consume much...

Crea tu propia plantilla de proyectos

Crea tu propia plantilla de proyectos

En un post anterior [Crear plantillas personalizadas para Netbeans] vimos una forma sencilla que tiene Netbeans para fac...

Cascadia Code: la nueva fuente OpenSource de Microsoft

Cascadia Code: la nueva fuente OpenSource de Microsoft

Microsoft acaba de lanzar Cascadia Code una fuente monoespaciada enfocada en proporcionar una mejor experiencia en conso...

Gestión de Stock (Parte 2)

Gestión de Stock (Parte 2)

Continuando con el desarrollo de la aplicación (Parte 1), abrimos Netbeans y creamos un nuevo proyecto al que llamaremos...

Esteganografía y encriptación de imágenes en Linux

Esteganografía y encriptación de imágenes en Linux

En un post anterior conocimos una herramienta Open Source con un conjunto de herramientas para el trabajo con imágenes e...

Personalizar JTabbedPane con Netbeans

Personalizar JTabbedPane con Netbeans

Crear una librería swing para java utilizando Netbeans no es nada del otro mundo y la cantidad de código que vayamos a e...

1 comentario en “Proyecto Ascii Art (metodo de Black/white)”

  1. Julio Orozco dice:

    Hola Jc-mouse muchisimas gracias por este proyecto me has iluminado a realizar un reconocedor de imagenes como un OCR, parte de tu codigo me va a servir mucho, una pregunta porque en blanco es -1 y en negro -16777216 esos parametros en que estan en byte, color alfa o en que estan?. Espero contar con tu apoyo muchas gracias.

Los comentarios estan cerrados

Comparte lo que sabes

Categorias

Últimas entradas

Quasar es un proyecto Open Source basado en el Framework Vue que nos permite desarrollar proyectos de todo tipo, por eje...

Continuando el post de «Introducción a Retrofit» donde realizamos una breve preparación a lo que es el uso de la librerí...

Editar un documento PDF no es tan sencillo como editar un archivo de texto por ejemplo, para editar archivos PDFs necesi...

¿Alguna vez tuviste la necesidad de hacer una captura de pantalla de una página web? Si es así, seguramente buscaste y d...

Herramientas

Generador de Enlaces a Whatsapp