Skip to content

Instantly share code, notes, and snippets.

@Yamakaja
Created September 28, 2017 07:09
Show Gist options
  • Save Yamakaja/7b84874e4afbe802ca4c893cdbe261a2 to your computer and use it in GitHub Desktop.
Save Yamakaja/7b84874e4afbe802ca4c893cdbe261a2 to your computer and use it in GitHub Desktop.
Terminal image viewer

Image Viewer

This snippet is not really useful in its current state, but demonstrates how images can be printed to the terminal.

Requirements

  • A terminal that supports RGB, like KDEs konsole
import java.lang.System;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public class ImageViewer {
private static final char[] chars = new char[] {' ', '\u2581', '\u2582', '\u2583', '\u2584', '\u2585', '\u2586', '\u2587', '\u2588'};
private static final char getChar(int alpha) {
return chars[Math.min((alpha * chars.length) / 255, 8)];
}
public static void main(String[] args) throws Exception {
StringBuilder builder = new StringBuilder();
BufferedImage image = ImageIO.read(new File(args[0]));
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
int color = image.getRGB(x,y);
builder.append("\u001b[38;2;");
builder.append(String.valueOf((color >> 16) & 0xFF));
builder.append(';');
builder.append(String.valueOf((color >> 8) & 0xFF));
builder.append(';');
builder.append(String.valueOf(color & 0xFF));
builder.append('m');
builder.append(getChar((color >>> 24) & 0xFF));
}
builder.append('\n');
}
System.out.print(builder.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment