ASCIIアートJavaの例

ascii-art-java、width = 616、height = 387

ASCII art グラフィックを作成する面白いJavaの例です。概念は単純で、イメージのRGBカラーを「整数モード」で取得し、後でカラーの整数をASCIIテキストで置き換えます。

P.Sこの例は、このhttp://stackoverflow.com/questions/7098972/ascii-art-java[post]

ASCIIArtService.java

package com.mkyong.service;

import java.awt.** ;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class ASCIIArtService {

    public static void main(String[]args) throws IOException {

        int width = 100;
        int height = 30;

       //BufferedImage image = ImageIO.read(new File("/Users/mkyong/Desktop/logo.jpg"));
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE__INT__RGB);
        Graphics g = image.getGraphics();
        g.setFont(new Font("SansSerif", Font.BOLD, 24));

        Graphics2D graphics = (Graphics2D) g;
        graphics.setRenderingHint(RenderingHints.KEY__TEXT__ANTIALIASING,
                RenderingHints.VALUE__TEXT__ANTIALIAS__ON);
        graphics.drawString("JAVA", 10, 20);

       //save this image
       //ImageIO.write(image, "png", new File("/users/mkyong/ascii-art.png"));

        for (int y = 0; y < height; y++) {
            StringBuilder sb = new StringBuilder();
            for (int x = 0; x < width; x++) {

                sb.append(image.getRGB(x, y) == -16777216 ? " " : "$");

            }

            if (sb.toString().trim().isEmpty()) {
                continue;
            }

            System.out.println(sb);
        }

    }

}

出力

                  $$$        $$$$$      $$$$         $$$$     $$$$$
                  $$$       $$$$$$$     $$$$         $$$$    $$$$$$$
                  $$$       $$$$$$$     $$$$$       $$$$$    $$$$$$$
                  $$$       $$$$$$$      $$$$       $$$$     $$$$$$$
                  $$$      $$$$ $$$$     $$$$$     $$$$$    $$$$ $$$$
                  $$$      $$$$ $$$$      $$$$     $$$$     $$$$ $$$$
                  $$$     $$$$$ $$$$$     $$$$     $$$$    $$$$$ $$$$$
                  $$$     $$$$   $$$$     $$$$$   $$$$$    $$$$   $$$$
                  $$$     $$$$   $$$$      $$$$   $$$$     $$$$   $$$$
                  $$$    $$$$$   $$$$$     $$$$$ $$$$$    $$$$$   $$$$$
                  $$$    $$$$$$$$$$$$$      $$$$ $$$$     $$$$$$$$$$$$$
          $$$$   $$$$    $$$$$$$$$$$$$      $$$$ $$$$     $$$$$$$$$$$$$
          $$$$   $$$$   $$$$$$$$$$$$$$$      $$$$$$$     $$$$$$$$$$$$$$$
          $$$$$ $$$$$   $$$$       $$$$      $$$$$$$     $$$$       $$$$
          $$$$$$$$$$$  $$$$$       $$$$$     $$$$$$$    $$$$$       $$$$$
           $$$$$$$$$   $$$$         $$$$      $$$$$     $$$$         $$$$
            $$$$$$$    $$$$         $$$$      $$$$$     $$$$         $$$$

参考文献

提供される整数のグラフィック形式]

ascii art image リンク://タグ/java/[java]