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](http://pngquant.org). 5 6## License 7 8[BSD](https://raw.github.com/pornel/pngquant/master/lib/COPYRIGHT). 9It can be linked with both free and closed-source software. 10 11## Download 12 13The [library](http://pngquant.org/lib) is currently a part of the [pngquant2 project](https://github.com/pornel/pngquant/tree/master/lib). 14 15Files needed for the library are only in the `lib/` directory inside the repository (and you can ignore the rest). 16 17## Compiling and Linking 18 19The library can be linked with ANSI C and C++ programs. It has no external dependencies. 20 21To build on Unix-like systems run: 22 23 make -C lib 24 25it will create `lib/libimagequant.a` which you can link with your program. 26 27 gcc yourprogram.c /path/to/lib/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 lib/*.c yourprogram.c 34 35### Compiling on Windows/Visual Studio 36 37The 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. There are 2 options for using `libimagequant` on Windows: 38 39 * Use Visual Studio **2013** (MSVC 18) and an [MSVC-compatible branch of the library](https://github.com/pornel/pngquant/tree/msvc/lib) 40 * Or use GCC from [MinGW](http://www.mingw.org). Use GCC to build `libimagequant.a` (using the instructions above for Unix) and add it along with `libgcc.a` (shipped with the MinGW compiler) to your VC project. 41 42## Overview 43 44The basic flow is: 45 461. Create attributes object and configure the library. 472. Create image object from RGBA bitmap or data source. 483. Perform quantization (generate palette). 494. Store remapped image and final palette. 505. Free memory. 51 52Please note that libimagequant only handles raw uncompressed bitmaps in memory and is completely independent of any file format. 53 54<p> 55 56 #include "lib/libimagequant.h" 57 58 liq_attr *attr = liq_attr_create(); 59 liq_image *image = liq_image_create_rgba(attr, bitmap, width, height, 0); 60 liq_result *res = liq_quantize_image(attr, image); 61 62 liq_write_remapped_image(res, image, bitmap, bitmap_size); 63 const liq_palette *pal = liq_get_palette(res); 64 65 // use image and palette here 66 67 liq_attr_destroy(attr); 68 liq_image_destroy(image); 69 liq_result_destroy(res); 70 71Functions returning `liq_error` return `LIQ_OK` (`0`) on success and non-zero on error. 72 73It'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. 74 75There are 3 ways to create image object for quantization: 76 77 * `liq_image_create_rgba()` for simple, contiguous RGBA bitmaps (width×height×4 bytes large array). 78 * `liq_image_create_rgba_rows()` for non-contiguous RGBA bitmaps (that have padding between rows or reverse order, e.g. BMP). 79 * `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). 80 81Note 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. 82 83## Functions 84 85---- 86 87 liq_attr* liq_attr_create(void); 88 89Returns 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. 90 91Returns `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). 92 93---- 94 95 liq_error liq_set_max_colors(liq_attr* attr, int colors); 96 97Specifies maximum number of colors to use. The default is 256. Instead of setting a fixed limit it's better to use `liq_set_quality()`. 98 99Returns `LIQ_VALUE_OUT_OF_RANGE` if number of colors is outside the range 2-256. 100 101---- 102 103 int liq_get_max_colors(liq_attr* attr); 104 105Returns the value set by `liq_set_max_colors()`. 106 107---- 108 109 liq_error liq_set_quality(liq_attr* attr, int minimum, int maximum); 110 111Quality is in range `0` (worst) to `100` (best) and values are analoguous to JPEG quality (i.e. `80` is usually good enough). 112 113Quantization 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. 114 115If 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_quantize_image()` will fail. The default minumum is `0` (proceeds regardless of quality). 116 117Quality measures how well the generated palette fits image given to `liq_quantize_image()`. If a different image is remapped with `liq_write_remapped_image()` then actual quality may be different. 118 119Regardless of the quality settings the number of colors won't exceed the maximum (see `liq_set_max_colors()`). 120 121Returns `LIQ_VALUE_OUT_OF_RANGE` if target is lower than minimum or any of them is outside the 0-100 range. 122Returns `LIQ_INVALID_POINTER` if `attr` appears to be invalid. 123 124 liq_attr *attr = liq_attr_create(); 125 liq_set_quality(attr, 50, 80); // use quality 80 if possible. Give up if quality drops below 50. 126 127---- 128 129 int liq_get_min_quality(liq_attr* attr); 130 131Returns the lower bound set by `liq_set_quality()`. 132 133---- 134 135 int liq_get_max_quality(liq_attr* attr); 136 137Returns the upper bound set by `liq_set_quality()`. 138 139---- 140 141 liq_image *liq_image_create_rgba(liq_attr *attr, void* bitmap, int width, int height, double gamma); 142 143Creates image object that represents a bitmap later used for quantization and remapping. The bitmap must be contiguous run of RGBA pixels (alpha is the last component, 0 = transparent, 255 = opaque). 144 145The bitmap must not be modified or freed until this object is freed with `liq_image_destroy()`. See also `liq_image_set_memory_ownership()`. 146 147`width` and `height` are dimensions in pixels. An image 10x10 pixel large will need 400-byte bitmap. 148 149`gamma` can be `0` for images with the typical 1/2.2 [gamma](http://en.wikipedia.org/wiki/Gamma_correction). 150Otherwise `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. 151 152Returns `NULL` on failure, e.g. if `bitmap` is `NULL` or `width`/`height` is <= 0. 153 154---- 155 156 liq_image *liq_image_create_rgba_rows(liq_attr *attr, void* rows[], int width, int height, double gamma); 157 158Same as `liq_image_create_rgba()`, but takes array of pointers to rows in the bitmap. This allows defining bitmaps with reversed rows (like in BMP), "stride" different than width or using only fragment of a larger bitmap, etc. 159 160`rows` array must have at least `height` elements and each row must be at least `width` RGBA pixels wide. 161 162 unsigned char *bitmap = …; 163 void *rows = malloc(height * sizeof(void*)); 164 int bytes_per_row = width * 4 + padding; // stride 165 for(int i=0; i < height; i++) { 166 rows[i] = bitmap + i * bytes_per_row; 167 } 168 liq_image *img = liq_image_create_rgba_rows(attr, rows, width, height, 0); 169 // … 170 liq_image_destroy(img); 171 free(rows); 172 173The row pointers and bitmap 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()`). 174 175See also `liq_image_create_rgba()` and `liq_image_create_custom()`. 176 177---- 178 179 liq_result *liq_quantize_image(liq_attr *attr, liq_image *input_image); 180 181Performs quantization (palette generation) based on settings in `attr` and pixels of the image. 182 183Returns `NULL` if quantization fails, e.g. due to limit set in `liq_set_quality()`. 184 185See `liq_write_remapped_image()`. 186 187---- 188 189 liq_error liq_set_dithering_level(liq_result *res, float dither_level); 190 191Enables/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. 192 193Precision of the dithering algorithm depends on the speed setting, see `liq_set_speed()`. 194 195Returns `LIQ_VALUE_OUT_OF_RANGE` if the dithering level is outside the 0-1 range. 196 197---- 198 199 liq_error liq_write_remapped_image(liq_result *result, liq_image *input_image, void *buffer, size_t buffer_size); 200 201Remaps the image to palette and writes its pixels to the given buffer, 1 pixel per byte. Buffer must be large enough to fit the entire image, i.e. width×height bytes large. For safety, pass size of the buffer as `buffer_size`. 202 203For best performance call `liq_get_palette()` *after* this function, as palette is improved during remapping. 204 205Returns `LIQ_BUFFER_TOO_SMALL` if given size of the buffer is not enough to fit the entire image. 206 207 int buffer_size = width*height; 208 char *buffer = malloc(buffer_size); 209 if (LIQ_OK == liq_write_remapped_image(result, input_image, buffer, buffer_size)) { 210 liq_palette *pal = liq_get_palette(result); 211 // save image 212 } 213 214See `liq_get_palette()` and `liq_write_remapped_image_rows()`. 215 216Please note that it only writes raw uncompressed pixels to memory. It does not perform any 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. 217 218---- 219 220 const liq_palette *liq_get_palette(liq_result *result); 221 222Returns pointer to palette optimized for image that has been quantized or remapped (final refinements are applied to the palette during remapping). 223 224It'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. 225 226`liq_palette->count` contains number of colors (up to 256), `liq_palette->entries[n]` contains RGBA value for nth palette color. 227 228The palette is **temporary and read-only**. You must copy the palette elsewhere *before* calling `liq_result_destroy()`. 229 230Returns `NULL` on error. 231 232---- 233 234 void liq_attr_destroy(liq_attr *); 235 void liq_image_destroy(liq_image *); 236 void liq_result_destroy(liq_result *); 237 238Releases memory owned by the given object. Object must not be used any more after it has been freed. 239 240Freeing `liq_result` also frees any `liq_palette` obtained from it. 241 242## Advanced Functions 243 244---- 245 246 liq_error liq_set_speed(liq_attr* attr, int speed); 247 248Higher speed levels disable expensive algorithms and reduce quantization precision. The default speed is `3`. 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. 249 250High speeds combined with `liq_set_quality()` will use more colors than necessary and will be less likely to meet minimum required quality. 251 252<table><caption>Features dependent on speed</caption> 253<tr><th>Noise-sensitive dithering</th><td>speed 1 to 5</td></tr> 254<tr><th>Forced posterization</th><td>8-10 or if image has more than million colors</td></tr> 255<tr><th>Quantization error known</th><td>1-7 or if minimum quality is set</td></tr> 256<tr><th>Additional quantization techniques</th><td>1-6</td></tr> 257</table> 258 259Returns `LIQ_VALUE_OUT_OF_RANGE` if the speed is outside the 1-10 range. 260 261---- 262 263 int liq_get_speed(liq_attr* attr); 264 265Returns the value set by `liq_set_speed()`. 266 267---- 268 269 liq_error liq_set_min_opacity(liq_attr* attr, int min); 270 271Alpha values higher than this will be rounded to opaque. This is a workaround for Internet Explorer 6 that truncates semitransparent values to completely transparent. The default is `255` (no change). 238 is a suggested value. 272 273Returns `LIQ_VALUE_OUT_OF_RANGE` if the value is outside the 0-255 range. 274 275---- 276 277 int liq_get_min_opacity(liq_attr* attr); 278 279Returns the value set by `liq_set_min_opacity()`. 280 281---- 282 283 liq_set_min_posterization(liq_attr* attr, int bits); 284 285Ignores 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). 286 287Returns `LIQ_VALUE_OUT_OF_RANGE` if the value is outside the 0-4 range. 288 289---- 290 291 int liq_get_min_posterization(liq_attr* attr); 292 293Returns the value set by `liq_set_min_posterization()`. 294 295---- 296 297 liq_set_last_index_transparent(liq_attr* attr, int is_last); 298 299`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. 300 301---- 302 303 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); 304 305<p> 306 307 void image_get_rgba_row_callback(liq_color row_out[], int row_index, int width, void *user_info) { 308 for(int column_index=0; column_index < width; column_index++) { 309 row_out[column_index] = /* generate pixel at (row_index, column_index) */; 310 } 311 } 312 313Creates 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. 314 315`user_info` value will be passed to the callback. It may be useful for storing pointer to program's internal representation of the image. 316 317The 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. 318 319The 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. 320 321To use RGB image: 322 323 void rgb_to_rgba_callback(liq_color row_out[], int row_index, int width, void *user_info) { 324 unsigned char *rgb_row = ((unsigned char *)user_info) + 3*width*row_index; 325 326 for(int i=0; i < width; i++) { 327 row_out[i].r = rgb_row[i*3]; 328 row_out[i].g = rgb_row[i*3+1]; 329 row_out[i].b = rgb_row[i*3+2]; 330 row_out[i].a = 255; 331 } 332 } 333 liq_image *img = liq_image_create_custom(attr, rgb_to_rgba_callback, rgb_bitmap, width, height, 0); 334 335The 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. 336 337---- 338 339 liq_error liq_image_set_memory_ownership(liq_image *image, int ownership_flags); 340 341Passes ownership of bitmap and/or rows memory 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()`). 342 343* `LIQ_OWN_PIXELS` makes bitmap owned by the object. The bitmap will be freed automatically at any point when it's no longer needed. If you set this flag you must **not** free the bitmap yourself. If the image has been created with `liq_image_create_rgba_rows()` then the bitmap address is assumed to be the lowest address of any row. 344 345* `LIQ_OWN_ROWS` makes array of row pointers (but not bitmap 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()`. 346 347These flags can be combined with binary *or*, i.e. `LIQ_OWN_PIXELS | LIQ_OWN_ROWS`. 348 349This function must not be used if the image has been created with `liq_image_create_custom()`. 350 351Returns `LIQ_VALUE_OUT_OF_RANGE` if invalid flags are specified or image is not backed by a bitmap. 352 353---- 354 355 liq_error liq_write_remapped_image_rows(liq_result *result, liq_image *input_image, unsigned char **row_pointers); 356 357Similar 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. 358 359For best performance call `liq_get_palette()` *after* this function, as remapping may change the palette. 360 361Returns `LIQ_INVALID_POINTER` if `result` or `input_image` is `NULL`. 362 363---- 364 365 double liq_get_quantization_error(liq_result *result); 366 367Returns mean square error of quantization (square of difference between pixel values in the original image and remapped image). Alpha channel and gamma correction are taken into account, so the result isn't exactly the mean square error of all channels. 368 369For most images MSE 1-5 is excellent. 7-10 is OK. 20-30 will have noticeable errors. 100 is awful. 370 371This function should be called *after* `liq_write_remapped_image()`. It may return `-1` if the value is not available (this is affected by `liq_set_speed()` and `liq_set_quality()`). 372 373---- 374 375 double liq_get_quantization_quality(liq_result *result); 376 377Analoguous 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()`. 378 379This function should be called *after* `liq_write_remapped_image()`. It may return `-1` if the value is not available (this is affected by `liq_set_speed()` and `liq_set_quality()`). 380 381This function can be used to add upper limit to quality options presented to the user, e.g. 382 383 liq_attr *attr = liq_attr_create(); 384 liq_image *img = liq_image_create_rgba(…); 385 liq_result *res = liq_quantize_image(attr, img); 386 int max_attainable_quality = liq_get_quantization_quality(res); 387 printf("Please select quality between 0 and %d: ", max_attainable_quality); 388 int user_selected_quality = prompt(); 389 if (user_selected_quality < max_attainable_quality) { 390 liq_set_quality(user_selected_quality, 0); 391 liq_result_destroy(res); 392 res = liq_quantize_image(attr, img); 393 } 394 liq_write_remapped_image(…); 395 396---- 397 398 void liq_set_log_callback(liq_attr*, liq_log_callback_function*, void *user_info); 399 400<p> 401 402 void log_callback_function(const liq_attr*, const char *message, void *user_info) {} 403 404---- 405 406 void liq_set_log_flush_callback(liq_attr*, liq_log_flush_callback_function*, void *user_info); 407<p> 408 409 void log_flush_callback_function(const liq_attr*, void *user_info) {} 410 411Sets up callback function to be called when the library reports work progress or errors. The callback must not call any library functions. 412 413`user_info` value will be passed to the callback. 414 415`NULL` callback clears the current callback. 416 417In the log callback the `message` is a zero-terminated string containing informative message to output. It is valid only until the callback returns. 418 419`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. 420 421---- 422 423 liq_attr* liq_attr_create_with_allocator(void* (*malloc)(size_t), void (*free)(void*)); 424 425Same as `liq_attr_create`, but uses given `malloc` and `free` replacements to allocate all memory used by the library. 426 427The `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. 428 429---- 430 431 liq_attr* liq_attr_copy(liq_attr *orig); 432 433Creates an independent copy of `liq_attr`. The copy should also be freed using `liq_attr_destroy()`. 434 435--- 436 437 liq_error liq_set_output_gamma(liq_result* res, double gamma); 438 439Sets 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. 440 441---- 442 443 int liq_image_get_width(const liq_image *img); 444 int liq_image_get_height(const liq_image *img); 445 double liq_get_output_gamma(const liq_result *result); 446 447Getters for `width`, `height` and `gamma` of the input image. 448 449If the input is invalid, these all return -1. 450 451--- 452 453 liq_error liq_image_add_fixed_color(liq_image* img, liq_color color); 454 455Reserves 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. 456 457RGB values of `liq_color` are assumed to have the same gamma as the image. 458 459It must be called before the image is quantized. 460 461Returns 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. 462 463--- 464 465 int liq_version(); 466 467Returns version of the library as an integer. Same as `LIQ_VERSION`. Human-readable version is defined as `LIQ_VERSION_STRING`. 468 469## Multithreading 470 471The library is stateless and doesn't use any global or thread-local storage. It doesn't use any locks. 472 473* Different threads can perform unrelated quantizations/remappings at the same time (e.g. each thread working on a different image). 474* 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). 475 476The 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. 477 478### OpenMP 479 480The library will parallelize some operations if compiled with OpenMP. 481 482You must not increase number of maximum threads after `liq_image` has been created, as it allocates some per-thread buffers. 483 484Callback of `liq_image_create_custom()` may be called from different threads at the same time. 485 486## Acknowledgements 487 488Thanks to Irfan Skiljan for helping test the first version of the library. 489 490The library is developed by [Kornel Lesiński](mailto:%20kornel@pngquant.org). 491