Convert PNG images to HolyC data structures for drawing in TempleOS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

92 lines
2.2 KiB

#include <stdio.h>
#include <stdlib.h>
#include <png.h>
int main(int argc, char **argv) {
if (argc != 4) {
printf("ERROR: %s <name> <input> <output>\n", argv[0]);
return EXIT_FAILURE;
}
printf("Opening %s\n", argv[2]);
FILE *fp = fopen(argv[2], "rb");
if (!fp) {
printf("ERROR: can't open %s\n", argv[2]);
return EXIT_FAILURE;
}
unsigned char header[8];
if (fread(header, 1, 8, fp) != 8) {
fclose(fp);
printf("ERROR: can't read %s\n", argv[2]);
return EXIT_FAILURE;
}
if (png_sig_cmp(header, 0, 8)) {
fclose(fp);
printf("ERROR: %s not recognized as a PNG file\n", argv[2]);
return EXIT_FAILURE;
}
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr) {
fclose(fp);
printf("ERROR: can't create read struct\n");
return EXIT_FAILURE;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
fclose(fp);
printf("ERROR: can't create info struct\n");
return EXIT_FAILURE;
}
if (setjmp(png_jmpbuf(png_ptr))) {
fclose(fp);
printf("ERROR: can't set jmpbuf\n");
return EXIT_FAILURE;
}
png_init_io(png_ptr, fp);
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
png_byte color_type = png_get_color_type(png_ptr, info_ptr);
if (color_type != PNG_COLOR_TYPE_PALETTE) {
fclose(fp);
printf("ERROR: %s is not palette-encoded\n", argv[2]);
return EXIT_FAILURE;
}
int width = png_get_image_width(png_ptr, info_ptr);
int height = png_get_image_height(png_ptr, info_ptr);
png_bytep *row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);
for (int y=0; y<height; y++) {
row_pointers[y] = (png_byte*) malloc(png_get_rowbytes(png_ptr,info_ptr));
}
png_read_image(png_ptr, row_pointers);
fclose(fp);
FILE *fOutput = fopen(argv[3], "w");
fprintf(fOutput, "#include \"PxBlot\"\nU8 %sBody[%d]={", argv[1], width*height);
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
unsigned int color = row_pointers[y][x];
if (color == 0) {
color = 0xff;
} else {
color--;
}
fprintf(fOutput, "%d,", color);
}
}
fseek(fOutput, -1, SEEK_CUR);
fprintf(fOutput, "};\nPxData %s={%d,%d,%sBody};", argv[1], width, height, argv[1]);
fclose(fOutput);
return EXIT_SUCCESS;
}