1# libimagequant—Image Quantization Library 2 3Small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images. 4It's powering [pngquant2](https://pngquant.org). 5 6## License 7 8Libimagequant is dual-licensed: 9 10* For Free/Libre Open Source Software it's available under GPL v3 or later with additional [copyright notices](https://raw.github.com/ImageOptim/libimagequant/master/COPYRIGHT) for older parts of the code. 11* For use in closed-source software, AppStore distribution, and other non-GPL uses, you can [obtain a commercial license](https://supso.org/projects/pngquant). Feel free to ask kornel@pngquant.org for details and custom licensing terms if you need them. 12 13## Download 14 15The [library](https://pngquant.org/lib) is currently a part of the [pngquant2 project](https://pngquant.org). [Repository](https://github.com/ImageOptim/libimagequant). 16 17## Compiling and Linking 18 19The library can be linked with ANSI C, C++, [C#](https://github.com/ImageOptim/libimagequant/blob/master/libimagequant.cs), [Rust](https://github.com/pornel/libimagequant-rust), [Java](https://github.com/ImageOptim/libimagequant/tree/master/org/pngquant) and [Golang](https://github.com/larrabee/go-imagequant) programs. It has no external dependencies. 20 21To build on Unix-like systems run: 22 23 make static 24 25it will create `libimagequant.a` which you can link with your program. 26 27 gcc yourprogram.c /path/to/libimagequant.a 28 29On BSD, use `gmake` (GNU make) rather than the native `make`. 30 31Alternatively you can compile the library with your program simply by including all `.c` files (and define `NDEBUG` to get a fast version): 32 33 gcc -std=c99 -O3 -DNDEBUG libimagequant/*.c yourprogram.c 34 35### Building for use in Rust programs 36 37In [Rust](https://www.rust-lang.org/) you can use Cargo to build the library. Add [`imagequant`](https://crates.io/crates/imagequant) to dependencies of the Rust program. You can also use `cargo build` in [`imagequant-sys`](https://crates.io/crates/imagequant-sys) to build `libimagequant.a` for any C-compatible language. 38 39### Building for Java JNI 40 41To build Java JNI interface, ensure `JAVA_HOME` is set to your JDK directory, and run: 42 43 # export JAVA_HOME=$(locate include/jni.h) # you may need to set JAVA_HOME first 44 make java 45 46It will create `libimagequant.jnilib` and classes in `org/pngquant/`. 47 48On Windows run `make java-dll` and it'll create `libimagequant.dll` instead. 49 50### Compiling on Windows/Visual Studio 51 52The library can be compiled with any C compiler that has at least basic support for C99 (GCC, clang, ICC, C++ Builder, even Tiny C Compiler), but Visual Studio 2012 and older are not up to date with the 1999 C standard. Use Visual Studio **2015** and the [MSVC-compatible branch of the library](https://github.com/ImageOptim/libimagequant/tree/msvc). 53 54To build on Windows, install CMake and use it to generate a makefile/project for your build system. 55 56Build instructions 57 58 mkdir build 59 cd build 60 cmake .. 61 cmake --build . 62 63To generate a 64-bit Visual Studio project instead: 64 65 mkdir build 66 cd build 67 cmake -G "Visual Studio 15 2017 Win64" .. 68 cmake --build . 69 70### Building as shared library 71 72To build on Unix-like systems run: 73 74 ./configure --prefix=/usr 75 make libimagequant.so 76 77To install on Unix-like systems run: 78 79 make install 80 81 82 83## Overview 84 85The basic flow is: 86 871. Create attributes object and configure the library. 882. Create image object from RGBA pixels or data source. 893. Perform quantization (generate palette). 904. Store remapped image and final palette. 915. Free memory. 92 93Please note that libimagequant only handles raw uncompressed arrays of pixels in memory and is completely independent of any file format. 94 95<p> 96 /* See example.c for the full code! */ 97 98 #include "libimagequant.h" 99 100 liq_attr *attr = liq_attr_create(); 101 liq_image *image = liq_image_create_rgba(attr, example_bitmap_rgba, width, height, 0); 102 liq_result *res; 103 liq_image_quantize(image, attr, &res); 104 105 liq_write_remapped_image(res, image, example_bitmap_8bpp, example_bitmap_size); 106 const liq_palette *pal = liq_get_palette(res); 107 108 // Save the image and the palette now. 109 for(int i=0; i < pal->count; i++) { 110 example_copy_palette_entry(pal->entries[i]); 111 } 112 // You'll need a PNG library to write to a file. 113 example_write_image(example_bitmap_8bpp); 114 115 liq_result_destroy(res); 116 liq_image_destroy(image); 117 liq_attr_destroy(attr); 118 119Functions returning `liq_error` return `LIQ_OK` (`0`) on success and non-zero on error. 120 121It's safe to pass `NULL` to any function accepting `liq_attr`, `liq_image`, `liq_result` (in that case the error code `LIQ_INVALID_POINTER` will be returned). These objects can be reused multiple times. 122 123There are 3 ways to create image object for quantization: 124 125 * `liq_image_create_rgba()` for simple, contiguous RGBA pixel arrays (width×height×4 bytes large bitmap). 126 * `liq_image_create_rgba_rows()` for non-contiguous RGBA pixel arrays (that have padding between rows or reverse order, e.g. BMP). 127 * `liq_image_create_custom()` for RGB, ABGR, YUV and all other formats that can be converted on-the-fly to RGBA (you have to supply the conversion function). 128 129Note that "image" here means raw uncompressed pixels. If you have a compressed image file, such as PNG, you must use another library (e.g. libpng or lodepng) to decode it first. 130 131You'll find full example code in "example.c" file in the library source directory. 132 133## Functions 134 135---- 136 137 liq_attr* liq_attr_create(void); 138 139Returns object that will hold initial settings (attributes) for the library. The object should be freed using `liq_attr_destroy()` after it's no longer needed. 140 141Returns `NULL` in the unlikely case that the library cannot run on the current machine (e.g. the library has been compiled for SSE-capable x86 CPU and run on VIA C3 CPU). 142 143---- 144 145 liq_error liq_set_max_colors(liq_attr* attr, int colors); 146 147Specifies maximum number of colors to use. The default is 256. Instead of setting a fixed limit it's better to use `liq_set_quality()`. 148 149The first argument is attributes object from `liq_attr_create()`. 150 151Returns `LIQ_VALUE_OUT_OF_RANGE` if number of colors is outside the range 2-256. 152 153---- 154 155 int liq_get_max_colors(liq_attr* attr); 156 157Returns the value set by `liq_set_max_colors()`. 158 159---- 160 161 liq_error liq_set_quality(liq_attr* attr, int minimum, int maximum); 162 163Quality is in range `0` (worst) to `100` (best) and values are analoguous to JPEG quality (i.e. `80` is usually good enough). 164 165Quantization will attempt to use the lowest number of colors needed to achieve `maximum` quality. `maximum` value of `100` is the default and means conversion as good as possible. 166 167If it's not possible to convert the image with at least `minimum` quality (i.e. 256 colors is not enough to meet the minimum quality), then `liq_image_quantize()` will fail. The default minimum is `0` (proceeds regardless of quality). 168 169Quality measures how well the generated palette fits image given to `liq_image_quantize()`. If a different image is remapped with `liq_write_remapped_image()` then actual quality may be different. 170 171Regardless of the quality settings the number of colors won't exceed the maximum (see `liq_set_max_colors()`). 172 173The first argument is attributes object from `liq_attr_create()`. 174 175Returns `LIQ_VALUE_OUT_OF_RANGE` if target is lower than minimum or any of them is outside the 0-100 range. 176Returns `LIQ_INVALID_POINTER` if `attr` appears to be invalid. 177 178 liq_attr *attr = liq_attr_create(); 179 liq_set_quality(attr, 50, 80); // use quality 80 if possible. Give up if quality drops below 50. 180 181---- 182 183 int liq_get_min_quality(liq_attr* attr); 184 185Returns the lower bound set by `liq_set_quality()`. 186 187---- 188 189 int liq_get_max_quality(liq_attr* attr); 190 191Returns the upper bound set by `liq_set_quality()`. 192 193---- 194 195 liq_image *liq_image_create_rgba(liq_attr *attr, void* pixels, int width, int height, double gamma); 196 197Creates an object that represents the image pixels to be used for quantization and remapping. The pixel array must be contiguous run of RGBA pixels (alpha is the last component, 0 = transparent, 255 = opaque). 198 199The first argument is attributes object from `liq_attr_create()`. The same `attr` object should be used for the entire process, from creation of images to quantization. 200 201The `pixels` array must not be modified or freed until this object is freed with `liq_image_destroy()`. See also `liq_image_set_memory_ownership()`. 202 203`width` and `height` are dimensions in pixels. An image 10x10 pixel large will need a 400-byte array. 204 205If the `gamma` argument is `0`, then the default of 1/2.2 [gamma](https://en.wikipedia.org/wiki/Gamma_correction) is assumed, which is good for most sRGB images. 206Otherwise `gamma` must be > 0 and < 1, e.g. `0.45455` (1/2.2) or `0.55555` (1/1.8). Generated palette will use the same gamma unless `liq_set_output_gamma()` is used. If `liq_set_output_gamma` is not used, then it only affects whether brighter or darker areas of the image will get more palette colors allocated. 207 208Returns `NULL` on failure, e.g. if `pixels` is `NULL` or `width`/`height` is <= 0. 209 210---- 211 212 liq_image *liq_image_create_rgba_rows(liq_attr *attr, void* rows[], int width, int height, double gamma); 213 214Same as `liq_image_create_rgba()`, but takes an array of pointers to rows of pixels. This allows defining images with reversed rows (like in BMP), "stride" different than width or using only fragment of a larger bitmap, etc. 215 216The `rows` array must have at least `height` elements, and each row must be at least `width` RGBA pixels wide. 217 218 unsigned char *bitmap = …; 219 void *rows = malloc(height * sizeof(void*)); 220 int bytes_per_row = width * 4 + padding; // stride 221 for(int i=0; i < height; i++) { 222 rows[i] = bitmap + i * bytes_per_row; 223 } 224 liq_image *img = liq_image_create_rgba_rows(attr, rows, width, height, 0); 225 // … 226 liq_image_destroy(img); 227 free(rows); 228 229The row pointers and pixels must not be modified or freed until this object is freed with `liq_image_destroy()` (you can change that with `liq_image_set_memory_ownership()`). 230 231See also `liq_image_create_rgba()` and `liq_image_create_custom()`. 232 233---- 234 235 liq_error liq_image_quantize(liq_image *const input_image, liq_attr *const attr, liq_result **out_result); 236 237Performs quantization (palette generation) based on settings in `attr` (from `liq_attr_create()`) and pixels of the image. 238 239Returns `LIQ_OK` if quantization succeeds and sets `liq_result` pointer in `out_result`. The last argument is used for receiving the `result` object: 240 241 liq_result *result; 242 if (LIQ_OK == liq_image_quantize(img, attr, &result)) { // Note &result 243 // result pointer is valid here 244 } 245 246Returns `LIQ_QUALITY_TOO_LOW` if quantization fails due to limit set in `liq_set_quality()`. 247 248See `liq_write_remapped_image()`. 249 250If you want to generate one palette for multiple images at once, see `liq_histogram_create()`. 251 252---- 253 254 liq_error liq_set_dithering_level(liq_result *res, float dither_level); 255 256Enables/disables dithering in `liq_write_remapped_image()`. Dithering level must be between `0` and `1` (inclusive). Dithering level `0` enables fast non-dithered remapping. Otherwise a variation of Floyd-Steinberg error diffusion is used. 257 258Precision of the dithering algorithm depends on the speed setting, see `liq_set_speed()`. 259 260Returns `LIQ_VALUE_OUT_OF_RANGE` if the dithering level is outside the 0-1 range. 261 262---- 263 264 liq_error liq_write_remapped_image(liq_result *result, liq_image *input_image, void *buffer, size_t buffer_size); 265 266Remaps the image to palette and writes its pixels to the given buffer, 1 pixel per byte. 267 268The buffer must be large enough to fit the entire image, i.e. width×height bytes large. For safety, pass the size of the buffer as `buffer_size`. 269 270For best performance call `liq_get_palette()` *after* this function, as palette is improved during remapping (except when `liq_histogram_quantize()` is used). 271 272Returns `LIQ_BUFFER_TOO_SMALL` if given size of the buffer is not enough to fit the entire image. 273 274 int buffer_size = width*height; 275 char *buffer = malloc(buffer_size); 276 if (LIQ_OK == liq_write_remapped_image(result, input_image, buffer, buffer_size)) { 277 liq_palette *pal = liq_get_palette(result); 278 // save image 279 } 280 281See `liq_get_palette()`. 282 283The buffer is assumed to be contiguous, with rows ordered from top to bottom, and no gaps between rows. If you need to write rows with padding or upside-down order, then use `liq_write_remapped_image_rows()`. 284 285Please note that it only writes raw uncompressed pixels to memory. It does not perform any PNG compression. If you'd like to create a PNG file then you need to pass the raw pixel data to another library, e.g. libpng or lodepng. See `rwpng.c` in `pngquant` project for an example how to do that. 286 287---- 288 289 const liq_palette *liq_get_palette(liq_result *result); 290 291Returns pointer to palette optimized for image that has been quantized or remapped (final refinements are applied to the palette during remapping). 292 293It's valid to call this method before remapping, if you don't plan to remap any images or want to use same palette for multiple images. 294 295`liq_palette->count` contains number of colors (up to 256), `liq_palette->entries[n]` contains RGBA value for nth palette color. 296 297The palette is **temporary and read-only**. You must copy the palette elsewhere *before* calling `liq_result_destroy()`. 298 299Returns `NULL` on error. 300 301---- 302 303 void liq_attr_destroy(liq_attr *); 304 void liq_image_destroy(liq_image *); 305 void liq_result_destroy(liq_result *); 306 void liq_histogram_destroy(liq_histogram *); 307 308Releases memory owned by the given object. Object must not be used any more after it has been freed. 309 310Freeing `liq_result` also frees any `liq_palette` obtained from it. 311 312## Advanced Functions 313 314---- 315 316 liq_error liq_set_speed(liq_attr* attr, int speed); 317 318Higher speed levels disable expensive algorithms and reduce quantization precision. The default speed is `4`. Speed `1` gives marginally better quality at significant CPU cost. Speed `10` has usually 5% lower quality, but is 8 times faster than the default. 319 320High speeds combined with `liq_set_quality()` will use more colors than necessary and will be less likely to meet minimum required quality. 321 322<table><caption>Features dependent on speed</caption> 323<tr><th>Noise-sensitive dithering</th><td>speed 1 to 5</td></tr> 324<tr><th>Forced posterization</th><td>8-10 or if image has more than million colors</td></tr> 325<tr><th>Quantization error known</th><td>1-7 or if minimum quality is set</td></tr> 326<tr><th>Additional quantization techniques</th><td>1-6</td></tr> 327</table> 328 329Returns `LIQ_VALUE_OUT_OF_RANGE` if the speed is outside the 1-10 range. 330 331---- 332 333 int liq_get_speed(liq_attr* attr); 334 335Returns the value set by `liq_set_speed()`. 336 337---- 338 339 liq_error liq_set_min_opacity(liq_attr* attr, int min); 340 341This was a workaround for Internet Explorer 6, but because this browser is not used any more, this option has been deprecated and removed. 342 343---- 344 345 int liq_get_min_opacity(liq_attr* attr); 346 347This function has been deprecated. 348 349---- 350 351 liq_set_min_posterization(liq_attr* attr, int bits); 352 353Ignores given number of least significant bits in all channels, posterizing image to `2^bits` levels. `0` gives full quality. Use `2` for VGA or 16-bit RGB565 displays, `4` if image is going to be output on a RGB444/RGBA4444 display (e.g. low-quality textures on Android). 354 355Returns `LIQ_VALUE_OUT_OF_RANGE` if the value is outside the 0-4 range. 356 357---- 358 359 int liq_get_min_posterization(liq_attr* attr); 360 361Returns the value set by `liq_set_min_posterization()`. 362 363---- 364 365 liq_set_last_index_transparent(liq_attr* attr, int is_last); 366 367`0` (default) makes alpha colors sorted before opaque colors. Non-`0` mixes colors together except completely transparent color, which is moved to the end of the palette. This is a workaround for programs that blindly assume the last palette entry is transparent. 368 369---- 370 371 liq_image *liq_image_create_custom(liq_attr *attr, liq_image_get_rgba_row_callback *row_callback, void *user_info, int width, int height, double gamma); 372 373<p> 374 375 void image_get_rgba_row_callback(liq_color row_out[], int row_index, int width, void *user_info) { 376 for(int column_index=0; column_index < width; column_index++) { 377 row_out[column_index] = /* generate pixel at (row_index, column_index) */; 378 } 379 } 380 381Creates image object that will use callback to read image data. This allows on-the-fly conversion of images that are not in the RGBA color space. 382 383`user_info` value will be passed to the callback. It may be useful for storing pointer to program's internal representation of the image. 384 385The callback must read/generate `row_index`-th row and write its RGBA pixels to the `row_out` array. Row `width` is given for convenience and will always equal to image width. 386 387The callback will be called multiple times for each row. Quantization and remapping require at least two full passes over image data, so caching of callback's work makes no sense — in such case it's better to convert entire image and use `liq_image_create_rgba()` instead. 388 389To use RGB image: 390 391 void rgb_to_rgba_callback(liq_color row_out[], int row_index, int width, void *user_info) { 392 unsigned char *rgb_row = ((unsigned char *)user_info) + 3*width*row_index; 393 394 for(int i=0; i < width; i++) { 395 row_out[i].r = rgb_row[i*3]; 396 row_out[i].g = rgb_row[i*3+1]; 397 row_out[i].b = rgb_row[i*3+2]; 398 row_out[i].a = 255; 399 } 400 } 401 liq_image *img = liq_image_create_custom(attr, rgb_to_rgba_callback, rgb_bitmap, width, height, 0); 402 403The library doesn't support RGB bitmaps "natively", because supporting only single format allows compiler to inline more code, 4-byte pixel alignment is faster, and SSE instructions operate on 4 values at once, so alpha support is almost free. 404 405---- 406 407 liq_error liq_image_set_memory_ownership(liq_image *image, int ownership_flags); 408 409Passes ownership of image pixel data and/or its rows array to the `liq_image` object, so you don't have to free it yourself. Memory owned by the object will be freed at its discretion with `free` function specified in `liq_attr_create_with_allocator()` (by default it's stdlib's `free()`). 410 411* `LIQ_OWN_PIXELS` makes pixel array owned by the object. The pixels will be freed automatically at any point when it's no longer needed. If you set this flag you must **not** free the pixel array yourself. If the image has been created with `liq_image_create_rgba_rows()` then the starting address of the array of pixels is assumed to be the lowest address of any row. 412 413* `LIQ_OWN_ROWS` makes array of row pointers (but not the pixels pointed by these rows) owned by the object. Rows will be freed when object is deallocated. If you set this flag you must **not** free the rows array yourself. This flag is valid only if the object has been created with `liq_image_create_rgba_rows()`. 414 415These flags can be combined with binary *or*, i.e. `LIQ_OWN_PIXELS | LIQ_OWN_ROWS`. 416 417This function must not be used if the image has been created with `liq_image_create_custom()`. 418 419Returns `LIQ_VALUE_OUT_OF_RANGE` if invalid flags are specified or the image object only takes pixels from a callback. 420 421---- 422 423 liq_error liq_image_set_background(liq_image *image, liq_image *background_image); 424 425Analyze and remap this image with assumption that it will be always presented exactly on top of this background. 426 427When this image is remapped to a palette with a fully transparent color (use `liq_image_add_fixed_color()` to ensure this) pixels that are better represented by the background than the palette will be made transparent. This function can be used to improve quality of animated GIFs by setting previous animation frame as the background. 428 429This function takes full ownership of the background image, so you should **not** free the background object. It will be freed automatically together with the foreground image. 430 431Returns `LIQ_BUFFER_TOO_SMALL` if the background image has a different size than the foreground. 432 433---- 434 435 liq_error liq_image_set_importance_map(liq_image *image, unsigned char map[], size_t buffer_size, liq_ownership ownership); 436 437Impotance map controls which areas of the image get more palette colors. Pixels corresponding to 0 values in the map are completely ignored. The higher the value the more weight is placed on the given pixel, giving it higher chance of influencing the final palette. 438 439The map is one byte per pixel and must have the same size as the image (width×height bytes). `buffer_size` argument is used to double-check that. 440 441If the `ownership` is `LIQ_COPY_PIXELS` then the `map` content be copied immediately (it's up to you to ensure the `map` memory is freed). 442 443If the `ownership` is `LIQ_OWN_PIXELS` then the `map` memory will be owned by the image and will be freed automatically when the image is freed. If a custom allocator has been set using `liq_attr_create_with_allocator()`, the `map` must be allocated using the same allocator. 444 445Returns `LIQ_INVALID_POINTER` if any pointer is `NULL`, `LIQ_BUFFER_TOO_SMALL` if the `buffer_size` does not match the image size, and `LIQ_UNSUPPORTED` if `ownership` isn't a valid value. 446 447---- 448 449 liq_error liq_write_remapped_image_rows(liq_result *result, liq_image *input_image, unsigned char **row_pointers); 450 451Similar to `liq_write_remapped_image()`. Writes remapped image, at 1 byte per pixel, to each row pointed by `row_pointers` array. The array must have at least as many elements as height of the image, and each row must have at least as many bytes as width of the image. Rows must not overlap. 452 453For best performance call `liq_get_palette()` *after* this function, as remapping may change the palette (except when `liq_histogram_quantize()` is used). 454 455Returns `LIQ_INVALID_POINTER` if `result` or `input_image` is `NULL`. 456 457---- 458 459 double liq_get_quantization_error(liq_result *result); 460 461Returns mean square error of quantization (square of difference between pixel values in the source image and its remapped version). Alpha channel, gamma correction and approximate importance of pixels is taken into account, so the result isn't exactly the mean square error of all channels. 462 463For most images MSE 1-5 is excellent. 7-10 is OK. 20-30 will have noticeable errors. 100 is awful. 464 465This function may return `-1` if the value is not available (this happens when a high speed has been requested, the image hasn't been remapped yet, and quality limit hasn't been set, see `liq_set_speed()` and `liq_set_quality()`). The value is not updated when multiple images are remapped, it applies only to the image used in `liq_image_quantize()` or the first image that has been remapped. See `liq_get_remapping_error()`. 466 467---- 468 469 double liq_get_remapping_error(liq_result *result); 470 471Returns mean square error of last remapping done (square of difference between pixel values in the remapped image and its remapped version). Alpha channel and gamma correction are taken into account, so the result isn't exactly the mean square error of all channels. 472 473This function may return `-1` if the value is not available (this happens when a high speed has been requested or the image hasn't been remapped yet). 474 475---- 476 477 double liq_get_quantization_quality(liq_result *result); 478 479Analoguous to `liq_get_quantization_error()`, but returns quantization error as quality value in the same 0-100 range that is used by `liq_set_quality()`. 480 481It may return `-1` if the value is not available (see note in `liq_get_quantization_error()`). 482 483This function can be used to add upper limit to quality options presented to the user, e.g. 484 485 liq_attr *attr = liq_attr_create(); 486 liq_image *img = liq_image_create_rgba(…); 487 liq_result *res; 488 liq_image_quantize(img, attr, &res); 489 int max_attainable_quality = liq_get_quantization_quality(res); 490 printf("Please select quality between 0 and %d: ", max_attainable_quality); 491 int user_selected_quality = prompt(); 492 if (user_selected_quality < max_attainable_quality) { 493 liq_set_quality(user_selected_quality, 0); 494 liq_result_destroy(res); 495 liq_image_quantize(img, attr, &res); 496 } 497 liq_write_remapped_image(…); 498 499---- 500 501 double liq_get_remapping_quality(liq_result *result); 502 503Analoguous to `liq_get_remapping_error()`, but returns quantization error as quality value in the same 0-100 range that is used by `liq_set_quality()`. 504 505---- 506 507 void liq_set_log_callback(liq_attr*, liq_log_callback_function*, void *user_info); 508 509<p> 510 511 void log_callback_function(const liq_attr*, const char *message, void *user_info) {} 512 513---- 514 515 void liq_set_log_flush_callback(liq_attr*, liq_log_flush_callback_function*, void *user_info); 516<p> 517 518 void log_flush_callback_function(const liq_attr*, void *user_info) {} 519 520Sets up callback function to be called when the library reports status or errors. The callback must not call any library functions. 521 522`user_info` value will be passed through to the callback. It can be `NULL`. 523 524`NULL` callback clears the current callback. 525 526In the log callback the `message` is a zero-terminated string containing informative message to output. It is valid only until the callback returns, so you must copy it. 527 528`liq_set_log_flush_callback()` sets up callback function that will be called after the last log callback, which can be used to flush buffers and free resources used by the log callback. 529 530---- 531 532 void liq_set_progress_callback(liq_attr*, liq_progress_callback_function*, void *user_info); 533 void liq_result_set_progress_callback(liq_result*, liq_progress_callback_function*, void *user_info); 534 535<p> 536 537 int progress_callback_function(const liq_attr*, float progress_percent, void *user_info) {} 538 539Sets up callback function to be called while the library is processing images. The callback may abort processing by returning `0`. 540 541Setting callback to `NULL` clears the current callback. `liq_set_progress_callback` is for quantization progress, and `liq_result_set_progress_callback` is for remapping progress (currently only dithered remapping reports progress). 542 543`user_info` value will be passed through to the callback. It can be `NULL`. 544 545The callback must not call any library functions. 546 547`progress_percent` is a value between 0 and 100 that estimates how much of the current task has been done. 548 549The callback should return `1` to continue the operation, and `0` to abort current operation. 550 551---- 552 553 liq_attr* liq_attr_create_with_allocator(void* (*malloc)(size_t), void (*free)(void*)); 554 555Same as `liq_attr_create`, but uses given `malloc` and `free` replacements to allocate all memory used by the library. 556 557The `malloc` function must return 16-byte aligned memory on x86 (and on other architectures memory aligned for `double` and pointers). Conversely, if your stdlib's `malloc` doesn't return appropriately aligned memory, you should use this function to provide aligned replacements. 558 559---- 560 561 liq_attr* liq_attr_copy(liq_attr *orig); 562 563Creates an independent copy of `liq_attr`. The copy should also be freed using `liq_attr_destroy()`. 564 565--- 566 567 liq_error liq_set_output_gamma(liq_result* res, double gamma); 568 569Sets gamma correction for generated palette and remapped image. Must be > 0 and < 1, e.g. `0.45455` for gamma 1/2.2 in PNG images. By default output gamma is same as gamma of the input image. 570 571---- 572 573 int liq_image_get_width(const liq_image *img); 574 int liq_image_get_height(const liq_image *img); 575 double liq_get_output_gamma(const liq_result *result); 576 577Getters for `width`, `height` and `gamma` of the input image. 578 579If the input is invalid, these all return -1. 580 581--- 582 583 liq_error liq_image_add_fixed_color(liq_image* img, liq_color color); 584 liq_error liq_histogram_add_fixed_color(liq_histogram* hist, liq_color color, double gamma); 585 586Reserves a color in the output palette created from this image. It behaves as if the given color was used in the image and was very important. 587 588RGB values of `liq_color` are assumed to have the same gamma as the image. For the histogram function, the `gamma` can be `0` (see `liq_image_create_rgba()`). 589 590It must be called before the image is quantized. 591 592Returns error if more than 256 colors are added. If image is quantized to fewer colors than the number of fixed colors added, then excess fixed colors will be ignored. 593 594For histograms see also a more flexible `liq_histogram_add_colors()`. 595 596--- 597 598 int liq_version(); 599 600Returns version of the library as an integer. Same as `LIQ_VERSION`. Human-readable version is defined as `LIQ_VERSION_STRING`. 601 602## Multiple images with the same palette 603 604It's possible to efficiently generate a single palette that is optimal for multiple images, e.g. for an APNG animation. This is done by collecting statistics of images in a `liq_histogram` object. 605 606 liq_attr *attr = liq_attr_create(); 607 liq_histogram *hist = liq_histogram_create(attr); 608 609 liq_image *image1 = liq_image_create_rgba(attr, example_bitmap_rgba1, width, height, 0); 610 liq_histogram_add_image(hist, attr, image1); 611 612 liq_image *image2 = liq_image_create_rgba(attr, example_bitmap_rgba2, width, height, 0); 613 liq_histogram_add_image(hist, attr, image2); 614 615 liq_result *result; 616 liq_error err = liq_histogram_quantize(attr, hist, &result); 617 if (LIQ_OK == err) { 618 // result will contain shared palette best for both image1 and image2 619 } 620 621--- 622 623 liq_histogram *liq_histogram_create(liq_attr *attr); 624 625Creates histogram object that will be used to collect color statistics from multiple images. It must be freed using `liq_histogram_destroy()`. 626 627All options should be set on `attr` before the histogram object is created. Options changed later may not have effect. 628 629--- 630 631 liq_error liq_histogram_add_image(liq_histogram *hist, liq_attr *attr, liq_image* image); 632 633"Learns" colors from the image, which will be later used to generate the palette. 634 635After the image is added to the histogram it may be freed to save memory (but it's more efficient to keep the image object if it's going to be used for remapping). 636 637Fixed colors added to the image are also added to the histogram. If total number of fixed colors exceeds 256, this function will fail with `LIQ_BUFFER_TOO_SMALL`. 638 639--- 640 641 liq_error liq_histogram_add_colors(liq_histogram *hist, liq_attr *attr, liq_histogram_entry entries[], int num_entries, double gamma); 642 643Alternative to `liq_histogram_add_image()`. Intead of counting colors in an image, it directly takes an array of colors and their counts (see `liq_histogram_entry` in `libimagequant.h`). This function is only useful if you already have a histogram of the image from another source. 644 645For description of gamma, see `liq_image_create_rgba()`. 646 647--- 648 649 liq_error liq_histogram_quantize(liq_histogram *const hist, liq_attr *const attr, liq_result **out_result); 650 651Generates palette from the histogram. On success returns `LIQ_OK` and writes `liq_result*` pointer to `out_result`. Use it as follows: 652 653 liq_result *result; 654 liq_error err = liq_histogram_quantize(attr, hist, &result); 655 if (LIQ_OK == err) { 656 // Use result here to remap and get palette 657 } 658 659Returns `LIQ_QUALITY_TOO_LOW` if the palette is worse than limit set in `liq_set_quality()`. One histogram object can be quantized only once. 660 661Palette generated using this function won't be improved during remapping. If you're generating palette for only one image, it's better to use `liq_image_quantize()`. 662 663## Working with GIF 664 665The library can generate palettes for GIF images. To ensure correct transparency is used you need to preprocess the image yourself and replace alpha values other than 0 or 255 with one of these. 666 667For animated GIFs see `liq_image_set_background()` which remaps images for GIF's "keep" frame disposal method. See [gif.ski](https://gif.ski). 668 669## Multithreading 670 671The library is stateless and doesn't use any global or thread-local storage. It doesn't use any locks. 672 673* Different threads can perform unrelated quantizations/remappings at the same time (e.g. each thread working on a different image). 674* The same `liq_attr`, `liq_result`, etc. can be accessed from different threads, but not at the same time (e.g. you can create `liq_attr` in one thread and free it in another). 675 676The library needs to sort unique colors present in the image. Although the sorting algorithm does few things to make stack usage minimal in typical cases, there is no guarantee against extremely degenerate cases, so threads should have automatically growing stack. 677 678### OpenMP 679 680The library can parallelize some operations if compiled with OpenMP. 681 682GCC 9 or later is required for correct OpenMP support. Older compilers *will cause bugs* when OpenMP is enabled. 683 684You must not increase number of maximum threads after `liq_image` has been created, as it allocates some per-thread buffers. 685 686Callback of `liq_image_create_custom()` may be called from different threads at the same time. 687 688## Acknowledgements 689 690Thanks to Irfan Skiljan for helping test the first version of the library. 691 692The library is developed by [Kornel Lesiński](mailto:%20kornel@pngquant.org). 693