Created
May 16, 2020 13:44
-
-
Save dbechrd/3d0ed1423b65454a961ea531f92aae0b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #define _CRT_SECURE_NO_WARNINGS | |
| #include <stdio.h> | |
| #define STB_IMAGE_IMPLEMENTATION | |
| #include "stb_image.h" | |
| int w, h, channels; | |
| unsigned char *data; | |
| FILE *file; | |
| void cleanup() | |
| { | |
| if (data) stbi_image_free(data); | |
| if (file) fclose(file); | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| // TODO(dlb): Take these from argv if you want to use this program from command line. | |
| const char *in_file = "test.png"; | |
| const char *out_file = "text.txt"; | |
| // NOTE(dlb): The "4" here forces stb_image to always output RGBA arrays, even for textures | |
| // with less than 4 channels. Feel free to change this (see stb_image.h lines 124 - 160 | |
| // for details) | |
| data = stbi_load(in_file, &w, &h, &channels, 4); | |
| if (!data) { | |
| printf("Error: Failed to open %s for read.\n", out_file); | |
| cleanup(); | |
| return -1; | |
| } | |
| int bytes = w * h * 4; | |
| if (!bytes) { | |
| printf("Error: Image is 0 bytes.\n"); | |
| cleanup(); | |
| return -2; | |
| } | |
| file = fopen(out_file, "w"); | |
| if (!file) { | |
| printf("Error: Failed to open %s for write.\n", out_file); | |
| cleanup(); | |
| return -3; | |
| } | |
| fprintf(file, "unsigned char pixels_rgba[] = {\n "); | |
| fprintf(file, "0x%02x", data[0]); | |
| // how many columns to format the byte data in | |
| int format_columns = 16; | |
| for (int i = 1; i < bytes; i++) { | |
| fprintf(file, ", "); | |
| if (i % format_columns == 0 && i < bytes - 1) { | |
| fprintf(file, "\n "); | |
| } | |
| fprintf(file, "0x%02x", data[i]); | |
| } | |
| fprintf(file, "\n};"); | |
| cleanup(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment