Skip to content

Instantly share code, notes, and snippets.

@felipetavares
Created October 17, 2019 11:04
Show Gist options
  • Save felipetavares/7eb7fdf29fd0505095b8023dbf4f94a7 to your computer and use it in GitHub Desktop.
Save felipetavares/7eb7fdf29fd0505095b8023dbf4f94a7 to your computer and use it in GitHub Desktop.
Detect if a PNG has a palette and load palette+data with libpng
// This examples read a PNG and its palette
#include <png.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
int main() {
png_image img;
png_bytep img_data;
memset(&img, 0, sizeof(png_image));
img.version = PNG_IMAGE_VERSION;
if (!png_image_begin_read_from_file(&img, "png.png")) {
puts("Error reading PNG");
}
// This can be used to check if the PNG has a palette
printf("%d\n", img.format & PNG_FORMAT_FLAG_COLORMAP);
// If so we can read it
img.format = PNG_FORMAT_RGBA_COLORMAP;
printf("%d\n", PNG_IMAGE_COLORMAP_SIZE(img));
// To here
png_bytep colormap = malloc(PNG_IMAGE_COLORMAP_SIZE(img));
img_data = malloc(sizeof(uint8_t)*PNG_IMAGE_SIZE(img));
if (png_image_finish_read(&img, NULL, img_data, 0, colormap) == 0) {
puts("Error reading PNG");
}
// Palette (first entry)
printf("%d %d %d %d\n", colormap[0], colormap[1], colormap[2], colormap[3]);
// Image (first pixel)
printf("%d\n", img_data[0]);
free(colormap);
free(img_data);
png_image_free(&img);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment