Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Create image with ASCII chars ordered by intensity
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.*;
* Create an ASCII letters sorted by intensity. By including the inverse letters
* the number of combinations are increased.
* The input is expected to be a file with ascii letters organized in 16x16.
* An example of such image is:
public class AsciiArtGenerator {
public static void main(String[] args) {
if (args.length != 2){
System.out.println("Usage [input] [output]");
BufferedImage bufferedImage = File(args[0]));
int width = bufferedImage.getWidth()/16;
int height = bufferedImage.getHeight()/16;
Vector<BufferedImage> subImages = new Vector<BufferedImage>();
for (int i=0;i<16;i++){
for (int j=0;j<16;j++){
BufferedImage subImage = bufferedImage.getSubimage(i * width, j * height, width, height);
BufferedImage invImg = getInverseImage(subImage);
Collections.sort(subImages, new Comparator<BufferedImage>() {
public int compare(BufferedImage b1, BufferedImage b2) {
int l1 = getLight(b1);
int l2 = getLight(b2);
return l1-l2;
BufferedImage bi = new BufferedImage(width*subImages.size()/2,height,BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
// only consider every second char, since we only want 256 chars
for (int i=0;i<subImages.size()/2;i++){
ImageIO.write(bi,"png",new File(args[1]));
catch (Exception e){
public static BufferedImage getInverseImage(BufferedImage bufferedImage){
BufferedImage copy = new BufferedImage(bufferedImage.getWidth(),bufferedImage.getHeight(),BufferedImage.TYPE_INT_RGB);
for (int x=0;x<copy.getWidth();x++){
for (int y=0;y<copy.getHeight();y++){
int rgb = bufferedImage.getRGB(x,y);
int flippedRGB = 0xffffff ^ rgb;
return copy;
private static Map<BufferedImage,Integer> cache = new HashMap<BufferedImage, Integer>();
private static int getLight(BufferedImage img){
Integer res = cache.get(img);
if (res != null){
return res;
res = 0;
final int white = -1;
for (int i=0;i<img.getWidth();i++){
for (int j=0;j<img.getHeight();j++){
int rgb = img.getRGB(i,j);
if (rgb!=white){
return res;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.