Skip to content

Instantly share code, notes, and snippets.

@chrissearle
Last active November 23, 2021 07:22
Show Gist options
  • Save chrissearle/300fb63069cceae638d0cb4874ecdf0f to your computer and use it in GitHub Desktop.
Save chrissearle/300fb63069cceae638d0cb4874ecdf0f to your computer and use it in GitHub Desktop.
Convert PNG To RGB565 For Adafruit_GFX TFT
/**
* Could't get adafruit's image reader working on Teensy 4.1 - doesn't seem to be compatible with
* Teensy's version of the SD card library
*
* But - the TFT object has this method:
*
* void Adafruit_GFX::drawRGBBitmap(
* int16_t x,
* int16_t y,
* uint16_t * bitmap,
* int16_t w,
* int16_t h
* )
*
* So - we need the image as a pointer to a list of uint16_t where each entry is a pixel in rgb565
*
* This conversion takes (for me) a PNG and dumps out the pixel array so it can be directly used in a
* C header file.
*/
import javax.imageio.ImageIO;
import java.io.File;
import java.awt.image.BufferedImage;
class Convert {
public static void main(String[] args) {
try {
BufferedImage image = ImageIO.read(new File(args[0]));
System.out.printf("uint16_t pcolors[%d] = {", image.getHeight() * image.getWidth());
String sep = "";
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
int pixel = image.getRGB(x, y);
int rgb565 = ((pixel & 0xf80000) >> 8) | ((pixel & 0xfc00) >> 5) | ((pixel & 0xf8) >> 3);
System.out.printf("%s%d", sep, rgb565);
sep = ", ";
}
}
System.out.printf("};%n");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment