ascii java_ASCII Art Java example

2465902fb7084f2acf03923960347577.png

A funny Java example to create an ASCII art graphic. The concept is simple, get the image’s rgb color in “integer mode”, later, replace the color’s integer with ascii text.

P.S This example is credited for this 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);

Output

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

What is -1677216?

The color code, in this case all colors "-1677216" are replaced with empty " ". This is the idea to generate the ASCII art graphic. Try load an image, and print out the rgb color, you will noticed that different color has different code.

References

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值