| 25 | #include "libimagequant.h" |
| 26 | |
| 27 | int main(int argc, char *argv[]) { |
| 28 | if (argc < 2) { |
| 29 | fprintf(stderr, "Please specify a path to a PNG file\n"); |
| 30 | return EXIT_FAILURE; |
| 31 | } |
| 32 | |
| 33 | const char *input_png_file_path = argv[1]; |
| 34 | |
| 35 | // Load PNG file and decode it as raw RGBA pixels |
| 36 | // This uses lodepng library for PNG reading (not part of libimagequant) |
| 37 | |
| 38 | unsigned int width, height; |
| 39 | unsigned char *raw_rgba_pixels; |
| 40 | unsigned int status = lodepng_decode32_file(&raw_rgba_pixels, &width, &height, input_png_file_path); |
| 41 | if (status) { |
| 42 | fprintf(stderr, "Can't load %s: %s\n", input_png_file_path, lodepng_error_text(status)); |
| 43 | return EXIT_FAILURE; |
| 44 | } |
| 45 | |
| 46 | // Use libimagequant to make a palette for the RGBA pixels |
| 47 | |
| 48 | liq_attr *handle = liq_attr_create(); |
| 49 | liq_image *input_image = liq_image_create_rgba(handle, raw_rgba_pixels, width, height, 0); |
| 50 | // You could set more options here, like liq_set_quality |
| 51 | liq_result *quantization_result; |
| 52 | if (liq_image_quantize(input_image, handle, &quantization_result) != LIQ_OK) { |
| 53 | fprintf(stderr, "Quantization failed\n"); |
| 54 | return EXIT_FAILURE; |
| 55 | } |
| 56 | |
| 57 | // Use libimagequant to make new image pixels from the palette |
| 58 | |
| 59 | size_t pixels_size = width * height; |
| 60 | unsigned char *raw_8bit_pixels = malloc(pixels_size); |
| 61 | liq_set_dithering_level(quantization_result, 1.0); |
| 62 | |
| 63 | liq_write_remapped_image(quantization_result, input_image, raw_8bit_pixels, pixels_size); |
| 64 | const liq_palette *palette = liq_get_palette(quantization_result); |
| 65 | |
| 66 | // Save converted pixels as a PNG file |
| 67 | // This uses lodepng library for PNG writing (not part of libimagequant) |
| 68 | |
| 69 | LodePNGState state; |
| 70 | lodepng_state_init(&state); |
| 71 | state.info_raw.colortype = LCT_PALETTE; |
| 72 | state.info_raw.bitdepth = 8; |
| 73 | state.info_png.color.colortype = LCT_PALETTE; |
| 74 | state.info_png.color.bitdepth = 8; |
| 75 | |
| 76 | for(int i=0; i < palette->count; i++) { |
| 77 | lodepng_palette_add(&state.info_png.color, palette->entries[i].r, palette->entries[i].g, palette->entries[i].b, palette->entries[i].a); |
| 78 | lodepng_palette_add(&state.info_raw, palette->entries[i].r, palette->entries[i].g, palette->entries[i].b, palette->entries[i].a); |
| 79 | } |
| 80 | |
| 81 | unsigned char *output_file_data; |
| 82 | size_t output_file_size; |
| 83 | unsigned int out_status = lodepng_encode(&output_file_data, &output_file_size, raw_8bit_pixels, width, height, &state); |
| 84 | if (out_status) { |
nothing calls this directly
no test coverage detected