alternate StringBuilder implementation. add function to convert RGB components to 2-digit hex strings

This commit is contained in:
Gered 2014-04-01 22:57:21 -04:00
parent b7363d3a81
commit 54dc8b0543
2 changed files with 1235 additions and 8 deletions

View file

@ -5,9 +5,33 @@ import java.awt.image.BufferedImage;
public class ImageToAscii {
static final char[] asciiChars = {'#', 'A', '@', '%', '$', '+', '=', '*', ':', ',', '.', ' '};
static final int numAsciiChars = asciiChars.length - 1;
static final int spanLength = "<span style=\"color:rgb(255,255,255);\">X</span>".length();
static final int spanLength = "<span style=\"color:#112233;\">X</span>".length();
static final int lineTerminatorLength = "<br>".length();
// copied from java.lang.Integer.digits (which is private so we can't just reference it, boourns)
static final char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
// modification of java.lang.Integer.toUnsignedString -- no garbage generated, but limited to max value
// of 255 ...hence the 'unsigned byte' thing :)
private static void unsignedByteToHex(int unsignedByte, StringBuilder sb) {
for (int i = 0; i < 2; ++i) {
int index = sb.length + 1 - i;
if (unsignedByte != 0) {
sb.chars[index] = digits[unsignedByte & 15];
unsignedByte >>>= 4;
} else
sb.chars[index] = '0';
}
sb.length += 2;
}
public static String convert(BufferedImage image, boolean useColor) {
final int width = image.getWidth();
final int height = image.getHeight();
@ -19,6 +43,7 @@ public class ImageToAscii {
final StringBuilder sb = new StringBuilder(maxLength);
final int[] pixels = image.getRGB(0, 0, width, height, null, 0, width);
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
final int argb = pixels[(y * width) + x];
@ -37,13 +62,11 @@ public class ImageToAscii {
final char pixelChar = asciiChars[charIndex > 0 ? charIndex : 0];
if (useColor) {
sb.append("<span style=\"color:rgb(");
sb.append(r);
sb.append(',');
sb.append(g);
sb.append(',');
sb.append(b);
sb.append(");\">");
sb.append("<span style=\"color:#");
unsignedByteToHex(r, sb);
unsignedByteToHex(g, sb);
unsignedByteToHex(b, sb);
sb.append(";\">");
sb.append(pixelChar);
sb.append("</span>");
} else

File diff suppressed because it is too large Load diff