Created
December 14, 2011 02:51
-
-
Save atduskgreg/1475033 to your computer and use it in GitHub Desktop.
trying to convert pixels to little endian byte array for thermal printing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.*; | |
byte[] imageBytes; | |
PImage img; | |
PrintWriter output; | |
void setup() { | |
size(500, 500); | |
img = loadImage("bmptest.bmp"); | |
imageBytes = loadBytes("bmptest.bmp"); | |
background(0); | |
fill(255); | |
stroke(255); | |
text("byte length: " + imageBytes.length, 10, img.height+20); | |
text("pixel count: " + img.pixels.length, 10, img.height+35); | |
text("pixels/8: " + img.pixels.length / 8, 10, img.height+50); | |
text("w: "+ img.width + " h: " +img.height, 10, img.height+65); | |
noLoop(); | |
output = createWriter("testimg.cpp"); | |
output.println("//------------------------------------------------------------------------------"); | |
output.println("// generated by Greg Borenstein's probably buggy Processing Sketch"); | |
output.println(); | |
output.println("//------------------------------------------------------------------------------"); | |
output.println(); | |
output.println("const unsigned char fakethesis [] = {"); | |
} | |
void draw() { | |
img.loadPixels(); | |
image(img, 0, 0); | |
int bCounter = 0; | |
String currentByte = ""; | |
int byteCount = 0; | |
for (int i = 3; i < img.pixels.length; i++) { | |
int pixelValue = int(map(brightness(img.pixels[i]), 0, 255, 1, 0)); | |
currentByte += pixelValue; | |
bCounter++; | |
if (bCounter > 7) { | |
currentByte = reverseString(currentByte); | |
String s = String.format("0x%02X", Integer.parseInt(currentByte, 2)); | |
output.print(s); | |
bCounter = 0; | |
currentByte = ""; | |
byteCount++; | |
if (i < img.pixels.length - 8) { | |
output.print(", "); | |
} | |
} | |
if ((i % 128) == 0 ) { | |
output.println(); | |
} | |
} | |
output.println("};"); | |
output.flush(); // Write the remaining data | |
output.close(); // Finish the file | |
} | |
String reverseString(String input){ | |
String output = ""; | |
for(int i = 0; i<input.length(); i++){ | |
output += input.charAt(input.length() - (i+1)); | |
} | |
return output; | |
} | |
int reverseEndianness(int x) { | |
ByteBuffer bbuf = ByteBuffer.allocate(8); | |
bbuf.order(ByteOrder.BIG_ENDIAN); | |
bbuf.putInt(x); | |
bbuf.order(ByteOrder.LITTLE_ENDIAN); | |
return bbuf.getInt(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment