Skip to content

Instantly share code, notes, and snippets.

@mortennobel
Created November 6, 2011 20:55
Show Gist options
  • Save mortennobel/1343465 to your computer and use it in GitHub Desktop.
Save mortennobel/1343465 to your computer and use it in GitHub Desktop.
Create image with ASCII chars ordered by intensity
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
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:
* http://www3.telus.net/anapan8/8x16%20font%20ASCII%20DOS%20437.gif
* http://www3.telus.net/anapan8/8x8%20font%20ASCII%20DOS%20437.gif
*/
public class AsciiArtGenerator {
public static void main(String[] args) {
if (args.length != 2){
System.out.println("Usage [input] [output]");
System.exit(-1);
}
try{
BufferedImage bufferedImage = ImageIO.read(new 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);
subImages.add(subImage);
BufferedImage invImg = getInverseImage(subImage);
subImages.add(invImg);
}
}
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++){
g.drawImage(subImages.get(i*2),i*width,0,null);
}
g.dispose();
ImageIO.write(bi,"png",new File(args[1]));
}
catch (Exception e){
e.printStackTrace();
}
}
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;
copy.setRGB(x,y,flippedRGB);
}
}
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){
res++;
}
}
}
cache.put(img,res);
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment