Chameleon Svn Source Tree


Source at commit 1322 created 9 years 5 months ago.
By meklort, Add doxygen to utils folder
2LodePNG version 20080927
4Copyright (c) 2005-2008 Lode Vandevenne
6This software is provided 'as-is', without any express or implied
7warranty. In no event will the authors be held liable for any damages
8arising from the use of this software.
10Permission is granted to anyone to use this software for any purpose,
11including commercial applications, and to alter it and redistribute it
12freely, subject to the following restrictions:
14 1. The origin of this software must not be misrepresented; you must not
15 claim that you wrote the original software. If you use this software
16 in a product, an acknowledgment in the product documentation would be
17 appreciated but is not required.
19 2. Altered source versions must be plainly marked as such, and must not be
20 misrepresented as being the original software.
22 3. This notice may not be removed or altered from any source
23 distribution.
26#ifndef LODEPNG_H
27#define LODEPNG_H
29#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
33/* ////////////////////////////////////////////////////////////////////////// */
34/* Code Sections */
35/* ////////////////////////////////////////////////////////////////////////// */
37/*The following defines can be commented disable code sections. Gives potential faster compile and smaller binary.*/
39#define LODEPNG_COMPILE_ZLIB /*deflate&zlib encoder and deflate&zlib decoder*/
40#define LODEPNG_COMPILE_PNG /*png encoder and png decoder*/
41//#define LODEPNG_COMPILE_DECODER /*deflate&zlib decoder and png decoder*/
42#define LODEPNG_COMPILE_ENCODER /*deflate&zlib encoder and png encoder*/
43#define LODEPNG_COMPILE_DISK /*the optional built in harddisk file loading and saving functions*/
44//#define LODEPNG_COMPILE_ANCILLARY_CHUNKS /*any code or struct datamember related to chunks other than IHDR, IDAT, PLTE, tRNS, IEND*/
45//#define LODEPNG_COMPILE_UNKNOWN_CHUNKS /*handling of unknown chunks*/
47/* ////////////////////////////////////////////////////////////////////////// */
48/* LodeFlate & LodeZlib Setting structs */
49/* ////////////////////////////////////////////////////////////////////////// */
52typedef struct LodeZlib_DecompressSettings
54 unsigned ignoreAdler32;
55} LodeZlib_DecompressSettings;
57extern const LodeZlib_DecompressSettings LodeZlib_defaultDecompressSettings;
58void LodeZlib_DecompressSettings_init(LodeZlib_DecompressSettings* settings);
62typedef struct LodeZlib_DeflateSettings /*deflate = compress*/
64 /*LZ77 related settings*/
65 unsigned btype; /*the block type for LZ*/
66 unsigned useLZ77; /*whether or not to use LZ77*/
67 unsigned windowSize; /*the maximum is 32768*/
68} LodeZlib_DeflateSettings;
70extern const LodeZlib_DeflateSettings LodeZlib_defaultDeflateSettings;
71void LodeZlib_DeflateSettings_init(LodeZlib_DeflateSettings* settings);
75/* ////////////////////////////////////////////////////////////////////////// */
76/* LodeFlate & LodeZlib */
77/* ////////////////////////////////////////////////////////////////////////// */
80/*This function reallocates the out buffer and appends the data.
81Either, *out must be NULL and *outsize must be 0, or, *out must be a valid buffer and *outsize its size in bytes.*/
82unsigned LodeZlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodeZlib_DecompressSettings* settings);
86/*This function reallocates the out buffer and appends the data.
87Either, *out must be NULL and *outsize must be 0, or, *out must be a valid buffer and *outsize its size in bytes.*/
88unsigned LodeZlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodeZlib_DeflateSettings* settings);
94/* ////////////////////////////////////////////////////////////////////////// */
95/* LodePNG */
96/* ////////////////////////////////////////////////////////////////////////// */
98/*LodePNG_chunk functions: These functions need as input a large enough amount of allocated memory.*/
100unsigned LodePNG_chunk_length(const unsigned char* chunk); /*get the length of the data of the chunk. Total chunk length has 12 bytes more.*/
102void LodePNG_chunk_type(char type[5], const unsigned char* chunk); /*puts the 4-byte type in null terminated string*/
103unsigned char LodePNG_chunk_type_equals(const unsigned char* chunk, const char* type); /*check if the type is the given type*/
105/*properties of PNG chunks gotten from capitalization of chunk type name, as defined by the standard*/
106unsigned char LodePNG_chunk_critical(const unsigned char* chunk); /*0: ancillary chunk, 1: it's one of the critical chunk types*/
107unsigned char LodePNG_chunk_private(const unsigned char* chunk); /*0: public, 1: private*/
108unsigned char LodePNG_chunk_safetocopy(const unsigned char* chunk); /*0: the chunk is unsafe to copy, 1: the chunk is safe to copy*/
110unsigned char* LodePNG_chunk_data(unsigned char* chunk); /*get pointer to the data of the chunk*/
111const unsigned char* LodePNG_chunk_data_const(const unsigned char* chunk); /*get pointer to the data of the chunk*/
113unsigned LodePNG_chunk_check_crc(const unsigned char* chunk); /*returns 0 if the crc is correct, 1 if it's incorrect*/
114void LodePNG_chunk_generate_crc(unsigned char* chunk); /*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/
116/*iterate to next chunks.*/
117unsigned char* LodePNG_chunk_next(unsigned char* chunk);
118const unsigned char* LodePNG_chunk_next_const(const unsigned char* chunk);
120/*add chunks to out buffer. It reallocs the buffer to append the data. returns error code*/
121unsigned LodePNG_append_chunk(unsigned char** out, size_t* outlength, const unsigned char* chunk); /*appends chunk that was already created, to the data. Returns pointer to start of appended chunk, or NULL if error happened*/
122unsigned LodePNG_create_chunk(unsigned char** out, size_t* outlength, unsigned length, const char* type, const unsigned char* data); /*appends new chunk to out. Returns pointer to start of appended chunk, or NULL if error happened; may change memory address of out buffer*/
124typedef struct LodePNG_InfoColor /*info about the color type of an image*/
126 /*header (IHDR)*/
127 unsigned colorType; /*color type*/
128 unsigned bitDepth; /*bits per sample*/
130 /*palette (PLTE)*/
131 unsigned char* palette; /*palette in RGBARGBA... order*/
132 size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/
134 /*transparent color key (tRNS)*/
135 unsigned key_defined; /*is a transparent color key given?*/
136 unsigned key_r; /*red component of color key*/
137 unsigned key_g; /*green component of color key*/
138 unsigned key_b; /*blue component of color key*/
139} LodePNG_InfoColor;
141void LodePNG_InfoColor_init(LodePNG_InfoColor* info);
142void LodePNG_InfoColor_cleanup(LodePNG_InfoColor* info);
143unsigned LodePNG_InfoColor_copy(LodePNG_InfoColor* dest, const LodePNG_InfoColor* source);
145/*Use these functions instead of allocating palette manually*/
146void LodePNG_InfoColor_clearPalette(LodePNG_InfoColor* info);
147unsigned LodePNG_InfoColor_addPalette(LodePNG_InfoColor* info, unsigned char r, unsigned char g, unsigned char b, unsigned char a); /*add 1 color to the palette*/
149/*additional color info*/
150unsigned LodePNG_InfoColor_getBpp(const LodePNG_InfoColor* info); /*bits per pixel*/
151unsigned LodePNG_InfoColor_getChannels(const LodePNG_InfoColor* info); /*amount of channels*/
152unsigned LodePNG_InfoColor_isGreyscaleType(const LodePNG_InfoColor* info); /*is it a greyscale type? (colorType 0 or 4)*/
153unsigned LodePNG_InfoColor_isAlphaType(const LodePNG_InfoColor* info); /*has it an alpha channel? (colorType 2 or 6)*/
156typedef struct LodePNG_Time /*LodePNG's encoder does not generate the current time. To make it add a time chunk the correct time has to be provided*/
158 unsigned year; /*2 bytes*/
159 unsigned char month; /*1-12*/
160 unsigned char day; /*1-31*/
161 unsigned char hour; /*0-23*/
162 unsigned char minute; /*0-59*/
163 unsigned char second; /*0-60 (to allow for leap seconds)*/
164} LodePNG_Time;
166typedef struct LodePNG_Text /*non-international text*/
168 size_t num;
169 char** keys; /*the keyword of a text chunk (e.g. "Comment")*/
170 char** strings; /*the actual text*/
171} LodePNG_Text;
173void LodePNG_Text_init(LodePNG_Text* text);
174void LodePNG_Text_cleanup(LodePNG_Text* text);
175unsigned LodePNG_Text_copy(LodePNG_Text* dest, const LodePNG_Text* source);
177/*Use these functions instead of allocating the char**s manually*/
178void LodePNG_Text_clear(LodePNG_Text* text);
179unsigned LodePNG_Text_add(LodePNG_Text* text, const char* key, const char* str); /*push back both texts at once*/
182typedef struct LodePNG_IText /*international text*/
184 size_t num;
185 char** keys; /*the English keyword of the text chunk (e.g. "Comment")*/
186 char** langtags; /*the language tag for this text's international language, ISO/IEC 646 string, e.g. ISO 639 language tag*/
187 char** transkeys; /*keyword translated to the international language - UTF-8 string*/
188 char** strings; /*the actual international text - UTF-8 string*/
189} LodePNG_IText;
191void LodePNG_IText_init(LodePNG_IText* text);
192void LodePNG_IText_cleanup(LodePNG_IText* text);
193unsigned LodePNG_IText_copy(LodePNG_IText* dest, const LodePNG_IText* source);
195/*Use these functions instead of allocating the char**s manually*/
196void LodePNG_IText_clear(LodePNG_IText* text);
197unsigned LodePNG_IText_add(LodePNG_IText* text, const char* key, const char* langtag, const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/
201typedef struct LodePNG_UnknownChunks /*unknown chunks read from the PNG, or extra chunks the user wants to have added in the encoded PNG*/
203 /*There are 3 buffers, one for each position in the PNG where unknown chunks can appear
204 each buffer contains all unknown chunks for that position consecutively
205 The 3 buffers are the unknown chunks between certain critical chunks:
207 unsigned char* data[3];
208 size_t datasize[3]; /*size in bytes of the unknown chunks, given for protection*/
210} LodePNG_UnknownChunks;
212void LodePNG_UnknownChunks_init(LodePNG_UnknownChunks* chunks);
213void LodePNG_UnknownChunks_cleanup(LodePNG_UnknownChunks* chunks);
214unsigned LodePNG_UnknownChunks_copy(LodePNG_UnknownChunks* dest, const LodePNG_UnknownChunks* src);
217typedef struct LodePNG_InfoPng /*information about the PNG image, except pixels and sometimes except width and height*/
219 /*header (IHDR), palette (PLTE) and transparency (tRNS)*/
220 unsigned width; /*width of the image in pixels (ignored by encoder, but filled in by decoder)*/
221 unsigned height; /*height of the image in pixels (ignored by encoder, but filled in by decoder)*/
222 unsigned compressionMethod; /*compression method of the original file*/
223 unsigned filterMethod; /*filter method of the original file*/
224 unsigned interlaceMethod; /*interlace method of the original file*/
225 LodePNG_InfoColor color; /*color type and bits, palette, transparency*/
229 /*suggested background color (bKGD)*/
230 unsigned background_defined; /*is a suggested background color given?*/
231 unsigned background_r; /*red component of suggested background color*/
232 unsigned background_g; /*green component of suggested background color*/
233 unsigned background_b; /*blue component of suggested background color*/
235 /*non-international text chunks (tEXt and zTXt)*/
236 LodePNG_Text text;
238 /*international text chunks (iTXt)*/
239 LodePNG_IText itext;
241 /*time chunk (tIME)*/
242 unsigned char time_defined; /*if 0, no tIME chunk was or will be generated in the PNG image*/
243 LodePNG_Time time;
245 /*phys chunk (pHYs)*/
246 unsigned phys_defined; /*is pHYs chunk defined?*/
247 unsigned phys_x;
248 unsigned phys_y;
249 unsigned char phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/
254 /*unknown chunks*/
255 LodePNG_UnknownChunks unknown_chunks;
258} LodePNG_InfoPng;
260void LodePNG_InfoPng_init(LodePNG_InfoPng* info);
261void LodePNG_InfoPng_cleanup(LodePNG_InfoPng* info);
262unsigned LodePNG_InfoPng_copy(LodePNG_InfoPng* dest, const LodePNG_InfoPng* source);
264typedef struct LodePNG_InfoRaw /*contains user-chosen information about the raw image data, which is independent of the PNG image*/
266 LodePNG_InfoColor color;
267} LodePNG_InfoRaw;
269void LodePNG_InfoRaw_init(LodePNG_InfoRaw* info);
270void LodePNG_InfoRaw_cleanup(LodePNG_InfoRaw* info);
271unsigned LodePNG_InfoRaw_copy(LodePNG_InfoRaw* dest, const LodePNG_InfoRaw* source);
274LodePNG_convert: Converts from any color type to 24-bit or 32-bit (later maybe more supported). return value = LodePNG error code
275The out buffer must have (w * h * bpp + 7) / 8, where bpp is the bits per pixel of the output color type (LodePNG_InfoColor_getBpp)
277unsigned LodePNG_convert(unsigned char* out, const unsigned char* in, LodePNG_InfoColor* infoOut, LodePNG_InfoColor* infoIn, unsigned w, unsigned h);
281typedef struct LodePNG_DecodeSettings
283 LodeZlib_DecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/
285 unsigned ignoreCrc; /*ignore CRC checksums*/
286 unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/
289 unsigned readTextChunks; /*if false but rememberUnknownChunks is true, they're stored in the unknown chunks*/
293 unsigned rememberUnknownChunks; /*store all bytes from unknown chunks in the InfoPng (off by default, useful for a png editor)*/
295} LodePNG_DecodeSettings;
297void LodePNG_DecodeSettings_init(LodePNG_DecodeSettings* settings);
299typedef struct LodePNG_Decoder
301 LodePNG_DecodeSettings settings;
302 LodePNG_InfoRaw infoRaw;
303 LodePNG_InfoPng infoPng; /*info of the PNG image obtained after decoding*/
304 unsigned error;
305} LodePNG_Decoder;
307void LodePNG_Decoder_init(LodePNG_Decoder* decoder);
308void LodePNG_Decoder_cleanup(LodePNG_Decoder* decoder);
309void LodePNG_Decoder_copy(LodePNG_Decoder* dest, const LodePNG_Decoder* source);
311/*decoding functions*/
312/*This function allocates the out buffer and stores the size in *outsize.*/
313void LodePNG_decode(LodePNG_Decoder* decoder, unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize);
314unsigned LodePNG_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize); /*return value is error*/
316unsigned LodePNG_decode32f(unsigned char** out, unsigned* w, unsigned* h, const char* filename);
318void LodePNG_inspect(LodePNG_Decoder* decoder, const unsigned char* in, size_t size); /*read the png header*/
324typedef struct LodePNG_EncodeSettings
326 LodeZlib_DeflateSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/
328 unsigned autoLeaveOutAlphaChannel; /*automatically use color type without alpha instead of given one, if given image is opaque*/
329 unsigned force_palette; /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). If colortype is 3, PLTE is _always_ created.*/
331 unsigned add_id; /*add LodePNG version as text chunk*/
332 unsigned text_compression; /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/
334} LodePNG_EncodeSettings;
336void LodePNG_EncodeSettings_init(LodePNG_EncodeSettings* settings);
338typedef struct LodePNG_Encoder
340 LodePNG_EncodeSettings settings;
341 LodePNG_InfoPng infoPng; /*the info specified by the user may not be changed by the encoder. The encoder will try to generate a PNG close to the given info.*/
342 LodePNG_InfoRaw infoRaw; /*put the properties of the input raw image in here*/
343 unsigned error;
344} LodePNG_Encoder;
346void LodePNG_Encoder_init(LodePNG_Encoder* encoder);
347void LodePNG_Encoder_cleanup(LodePNG_Encoder* encoder);
348void LodePNG_Encoder_copy(LodePNG_Encoder* dest, const LodePNG_Encoder* source);
350/*This function allocates the out buffer and stores the size in *outsize.*/
351void LodePNG_encode(LodePNG_Encoder* encoder, unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h);
352unsigned LodePNG_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h); /*return value is error*/
354unsigned LodePNG_encode32f(const char* filename, const unsigned char* image, unsigned w, unsigned h);
360/*free functions allowing to load and save a file from/to harddisk*/
361/*This function allocates the out buffer and stores the size in *outsize.*/
362unsigned LodePNG_loadFile(unsigned char** out, size_t* outsize, const char* filename);
363unsigned LodePNG_saveFile(const unsigned char* buffer, size_t buffersize, const char* filename);
369[ ] test if there are no memory leaks or security exploits - done a lot but needs to be checked often
370[ ] LZ77 encoder more like the one described in zlib - to make sure it's patentfree
371[ ] converting color to 16-bit types
372[ ] read all public PNG chunk types (but never let the color profile and gamma ones ever touch RGB values, that is very annoying for textures as well as images in a browser)
373[ ] make sure encoder generates no chunks with size > (2^31)-1
374[ ] partial decoding (stream processing)
375[ ] let the "isFullyOpaque" function check color keys and transparent palettes too
376[ ] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl"
377[ ] check compatibility with vareous compilers - done but needs to be redone for every newer version
378[ ] don't stop decoding on errors like 69, 57, 58 (make warnings that the decoder stores in the error at the very end? and make some errors just let it stop with this one chunk but still do the next ones)
379[ ] make option to choose if the raw image with non multiple of 8 bits per scanline should have padding bits or not, if people like storing raw images that way
385LodePNG Documentation
3880. table of contents
391 1. about
392 1.1. supported features
393 1.2. features not supported
394 2. C and C++ version
395 3. A note about security!
396 4. simple functions
397 4.1 C Simple Functions
398 4.2 C++ Simple Functions
399 5. decoder
400 6. encoder
401 7. color conversions
402 8. info values
403 9. error values
404 10. file IO
405 11. chunks and PNG editing
406 12. compiler support
407 13. examples
408 13.1. decoder example
409 13.2. encoder example
410 14. LodeZlib
411 15. changes
412 16. contact information
4151. about
418PNG is a file format to store raster images losslessly with good compression,
419supporting different color types. It can be implemented in a patent-free way.
421LodePNG is a PNG codec according to the Portable Network Graphics (PNG)
422Specification (Second Edition) - W3C Recommendation 10 November 2003.
424The specifications used are:
426*) Portable Network Graphics (PNG) Specification (Second Edition):
428*) RFC 1950 ZLIB Compressed Data Format version 3.3:
430*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3:
433The most recent version of LodePNG can currently be found at
436LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds
437extra functionality.
439LodePNG exists out of two files:
440-lodepng.h: the header file for both C and C++
441-lodepng.c(pp): give it the name lodepng.c or lodepng.cpp depending on your usage
443If you want to start using LodePNG right away without reading this doc, get the
444files lodepng_examples.c or lodepng_examples.cpp to see how to use it in code,
445or check the (smaller) examples in chapter 13 here.
447LodePNG is simple but only supports the basic requirements. To achieve
448simplicity, the following design choices were made: There are no dependencies
449on any external library. To decode PNGs, there's a Decoder struct or class that
450can convert any PNG file data into an RGBA image buffer with a single function
451call. To encode PNGs, there's an Encoder struct or class that can convert image
452data into PNG file data with a single function call. To read and write files,
453there are simple functions to convert the files to/from buffers in memory.
455This all makes LodePNG suitable for loading textures in games, demoscene
456productions, saving a screenshot, images in programs that require them for simple
457usage, ... It's less suitable for full fledged image editors, loading PNGs
458over network (it requires all the image data to be available before decoding can
459begin), life-critical systems, ...
460LodePNG has a standards conformant decoder and encoder, and supports the ability
461to make a somewhat conformant editor.
4631.1. supported features
466The following features are supported by the decoder:
468*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image, or the same color type as the PNG
469*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image
470*) Adam7 interlace and deinterlace for any color type
471*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk
472*) support for alpha channels, including RGBA color model, translucent palettes and color keying
473*) zlib decompression (inflate)
474*) zlib compression (deflate)
475*) CRC32 and ADLER32 checksums
476*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks.
477*) the following chunks are supported (generated/interpreted) by both encoder and decoder:
478 IHDR: header information
479 PLTE: color palette
480 IDAT: pixel data
481 IEND: the final chunk
482 tRNS: transparency for palettized images
483 tEXt: textual information
484 zTXt: compressed textual information
485 iTXt: international textual information
486 bKGD: suggested background color
487 pHYs: physical dimensions
488 tIME: modification time
4901.2. features not supported
493The following features are _not_ supported:
495*) some features needed to make a conformant PNG-Editor might be still missing.
496*) partial loading/stream processing. All data must be available and is processed in one call.
497*) The following public chunks are not supported but treated as unknown chunks by LodePNG
498 cHRM, gAMA, iCCP, sRGB, sBIT, hIST, sPLT
5012. C and C++ version
504The C version uses buffers allocated with alloc instead that you need to free()
505yourself. On top of that, you need to use init and cleanup functions for each
506struct whenever using a struct from the C version to avoid exploits and memory leaks.
508The C++ version has constructors and destructors that take care of these things,
509and uses std::vectors in the interface for storing data.
511Both the C and the C++ version are contained in this file! The C++ code depends on
512the C code, the C code works on its own.
514These files work without modification for both C and C++ compilers because all the
515additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers ignore
516it, and the C code is made to compile both with strict ISO C90 and C++.
518To use the C++ version, you need to rename the source file to lodepng.cpp (instead
519of lodepng.c), and compile it with a C++ compiler.
521To use the C version, you need to rename the source file to lodepng.c (instead
522of lodepng.cpp), and compile it with a C compiler.
5253. A note about security!
528Despite being used already and having received bug fixes whenever bugs were reported,
529LodePNG may still contain possible exploits.
531If you discover a possible exploit, please let me know, and it will be eliminated.
533When using LodePNG, care has to be taken with the C version of LodePNG, as well as the C-style
534structs when working with C++. The following conventions are used for all C-style structs:
536-if a struct has a corresponding init function, always call the init function when making a new one, to avoid exploits
537-if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks
538-if a struct has a corresponding copy function, use the copy function instead of "=". The destination must be inited already!
5414. "Simple" Functions
544For the most simple usage cases of loading and saving a PNG image, there
545are some simple functions that do everything in 1 call (instead of you
546having to instantiate a struct or class).
548The simple versions always use 32-bit RGBA color for the raw image, but
549still support loading arbitrary-colortype PNG images.
551The later sections of this manual are devoted to the complex versions, where
552you can use other color types and conversions.
5544.1 C Simple Functions
557The C simple functions have a "32" or "32f" in their name, and don't take a struct as
558parameter, unlike the non-simple ones (see more down in the documentation).
560unsigned LodePNG_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize);
562Load PNG from given buffer.
563As input, give an unsigned char* buffer gotten by loading the .png file and its size.
564As output, you get a dynamically allocated buffer of large enough size, and the width and height of the image.
565The buffer's size is w * h * 4. The image is in RGBA format.
566The return value is the error (0 if ok).
567You need to do free(out) after usage to clean up the memory.
569unsigned LodePNG_decode32f(unsigned char** out, unsigned* w, unsigned* h, const char* filename);
571Load PNG from disk, from file with given name.
572Same as decode32, except you give a filename instead of an input buffer.
574unsigned LodePNG_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h);
576Encode PNG into buffer.
577As input, give a image buffer of size w * h * 4, in RGBA format.
578As output, you get a dynamically allocated buffer and its size, which is a PNG file that can
579directly be saved in this form to the harddisk.
580The return value is the error (0 if ok).
581You need to do free(out) after usage to clean up the memory.
583unsigned LodePNG_encode32f(const char* filename, const unsigned char* image, unsigned w, unsigned h);
585Encode PNG into file on disk with given name.
586If the file exists, it's overwritten without warning!
587Same parameters as encode2, except the result is stored in a file instead of a dynamic buffer.
5894.2 C++ Simple Functions
592For decoding a PNG there are:
594unsigned LodePNG::decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const unsigned char* in, unsigned size);
595unsigned LodePNG::decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::vector<unsigned char>& in);
596unsigned LodePNG::decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h, const std::string& filename);
598These store the pixel data as 32-bit RGBA color in the out vector, and the width
599and height of the image in w and h.
600The 3 functions each have a different input type: The first as unsigned char
601buffer, the second as std::vector buffer, and the third allows you to give the
602filename in case you want to load the PNG from disk instead of from a buffer.
603The return value is the error (0 if ok).
605For encoding a PNG there are:
607unsigned LodePNG::encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h);
608unsigned LodePNG::encode(std::vector<unsigned char>& out, const std::vector<unsigned char>& in, unsigned w, unsigned h);
609unsigned LodePNG::encode(const std::string& filename, const std::vector<unsigned char>& in, unsigned w, unsigned h);
610unsigned LodePNG::encode(const std::string& filename, const unsigned char* in, unsigned w, unsigned h);
612Specify the width and height of the input image with w and h.
613You can choose to get the output in an std::vector or stored in a file, and
614the input can come from an std::vector or an unsigned char* buffer. The input
615buffer must be in RGBA format and the size must be w * h * 4 bytes.
617The first two functions append to the out buffer, they don't clear it, clear it
618first before encoding into a buffer that you expect to only contain this result.
620On the other hand, the functions that encode to a file will completely overwrite
621the original file without warning if it exists.
623The return value is the error (0 if ok).
6255. Decoder
628This is about the LodePNG_Decoder struct in the C version, and the
629LodePNG::Decoder class in the C++ version. The C++ version inherits
630from the C struct and adds functions in the interface.
632The Decoder class can be used to convert a PNG image to a raw image.
636-in C++:
637 declare a LodePNG::Decoder
638 call its decode member function with the parameters described below
640-in C more needs to be done due to the lack of constructors and destructors:
641 declare a LodePNG_Decoder struct
642 call LodePNG_Decoder_init with the struct as parameter
643 call LodePNG_Decode with the parameters described below
644 after usage, call LodePNG_Decoder_cleanup with the struct as parameter
645 after usage, free() the out buffer with image data that was created by the decode function
647The other parameters of the decode function are:
648*) out: this buffer will be filled with the raw image pixels
649*) in: pointer to the PNG image data or std::vector with the data
650*) size: the size of the PNG image data (not needed for std::vector version)
652After decoding you need to read the width and height of the image from the
653decoder, see further down in this manual to see how.
655There's also an optional function "inspect". It has the same parameters as decode except
656the "out" parameter. This function will read only the header chunk of the PNG
657image, and store the information from it in the LodePNG_InfoPng (see below).
658This allows knowing information about the image without decoding it. Only the
659header (IHDR) information is read by this, not text chunks, not the palette, ...
661During the decoding it's possible that an error can happen, for example if the
662PNG image was corrupted. To check if an error happened during the last decoding,
663check the value error, which is a member of the decoder struct.
664In the C++ version, use hasError() and getError() of the Decoder.
665The error codes are explained in another section.
667Now about colors and settings...
669The Decoder contains 3 components:
670*) LodePNG_InfoPng: it stores information about the PNG (the input) in an LodePNG_InfoPng struct, don't modify this one yourself
671*) Settings: you can specify a few other settings for the decoder to use
672*) LodePNG_InfoRaw: here you can say what type of raw image (the output) you want to get
674Some of the parameters described below may be inside the sub-struct "LodePNG_InfoColor color".
675In the C and C++ version, when using Info structs outside of the decoder or encoder, you need to use their
676init and cleanup functions, but normally you use the ones in the decoder that are already handled
677in the init and cleanup functions of the decoder itself.
681This contains information such as the original color type of the PNG image, text
682comments, suggested background color, etc... More details about the LodePNG_InfoPng struct
683are in another section.
685Because the dimensions of the image are important, there are shortcuts to get them in the
686C++ version: use decoder.getWidth() and decoder.getHeight().
687In the C version, use decoder.infoPng.width and decoder.infoPng.height.
691In the LodePNG_InfoRaw struct of the Decoder, you can specify which color type you want
692the resulting raw image to be. If this is different from the colorType of the
693PNG, then the decoder will automatically convert the result to your LodePNG_InfoRaw
694settings. Currently the following options are supported to convert to:
695-colorType 6, bitDepth 8: 32-bit RGBA
696-colorType 2, bitDepth 8: 24-bit RGB
697-other color types if it's exactly the same as that in the PNG image
699Palette of LodePNG_InfoRaw isn't used by the Decoder, when converting from palette color
700to palette color, the values of the pixels are left untouched so that the colors
701will change if the palette is different. Color key of LodePNG_InfoRaw is not used by the
702Decoder. If setting color_convert is false then LodePNG_InfoRaw is completely ignored,
703but it will be modified to match the color type of the PNG so will be overwritten.
705By default, 32-bit color is used for the result.
709The Settings can be used to ignore the errors created by invalid CRC and Adler32
710chunks, and to disable the decoding of tEXt chunks.
712There's also a setting color_convert, true by default. If false, no conversion
713is done, the resulting data will be as it was in the PNG (after decompression)
714and you'll have to puzzle the colors of the pixels together yourself using the
715color type information in the LodePNG_InfoPng.
7186. Encoder
721This is about the LodePNG_Encoder struct in the C version, and the
722LodePNG::Encoder class in the C++ version.
724The Encoder class can be used to convert raw image data into a PNG image.
726The PNG part of the encoder is working good, the zlib compression part is
727becoming quite fine but not as good as the official zlib yet, because it's not
728as fast and doesn't provide an as high compression ratio.
732-in C++:
733 declare a LodePNG::Encoder
734 call its encode member function with the parameters described below
736-in C more needs to be done due to the lack of constructors and destructors:
737 declare a LodePNG_Encoder struct
738 call LodePNG_Encoder_init with the struct as parameter
739 call LodePNG_Encode with the parameters described below
740 after usage, call LodePNG_Encoder_cleanup with the struct as parameter
741 after usage, free() the out buffer with PNG data that was created by the encode function
743The raw image given to the encoder is an unsigned char* buffer. You also have to
744specify the width and height of the raw image. The result is stored in a given
745buffer. These buffers can be unsigned char* pointers, std::vectors or dynamically
746allocated unsigned char* buffers that you have to free() yourself, depending on
747which you use.
749The parameters of the encode function are:
750*) out: in this buffer the PNG file data will be stored (it will be appended)
751*) in: vector of or pointer to a buffer containing the raw image
752*) w and h: the width and height of the raw image in pixels
754Make sure that the in buffer you provide, is big enough to contain w * h pixels
755of the color type specified by the LodePNG_InfoRaw.
757In the C version, you need to free() the out buffer after usage to avoid memory leaks.
758In the C version, you need to use the LodePNG_Encoder_init function before using the decoder,
759and the LodePNG_Encoder_cleanup function after using it.
760In the C++ version, you don't need to do this since RAII takes care of it.
762The encoder generates some errors but not for everything, because, unlike when
763decoding a PNG, when encoding one there aren't so much parameters of the input
764that can be corrupted. It's the responsibility of the user to make sure that all
765preconditions are satesfied, such as giving a correct window size, giving an
766existing btype, making sure the given buffer is large enough to contain an image
767with the given width and height and colortype, ... The encoder can generate
768some errors, see the section with the explanations of errors for those.
770Like the Decoder, the Encoder has 3 components:
771*) LodePNG_InfoRaw: here you say what color type of the raw image (the input) has
772*) Settings: you can specify a few settings for the encoder to use
773*) LodePNG_InfoPng: the same LodePNG_InfoPng struct as created by the Decoder. For the encoder,
774with this you specify how you want the PNG (the output) to be.
776Some of the parameters described below may be inside the sub-struct "LodePNG_InfoColor color".
777In the C and C++ version, when using Info structs outside of the decoder or encoder, you need to use their
778init and cleanup functions, but normally you use the ones in the encoder that are already handled
779in the init and cleanup functions of the decoder itself.
783The Decoder class stores information about the PNG image in an LodePNG_InfoPng object. With
784the Encoder you can do the opposite: you give it an LodePNG_InfoPng object, and it'll try
785to match the LodePNG_InfoPng you give as close as possible in the PNG it encodes. For
786example in the LodePNG_InfoPng you can specify the color type you want to use, possible
787tEXt chunks you want the PNG to contain, etc... For an explanation of all the
788values in LodePNG_InfoPng see a further section. Not all PNG color types are supported
789by the Encoder.
791Note that the encoder will only TRY to match the LodePNG_InfoPng struct you give.
792Some things are ignored by the encoder. The width and height of LodePNG_InfoPng are
793ignored as well, because instead the width and height of the raw image you give
794in the input are used. In fact the encoder currently uses only the following
795settings from it:
796-colorType: the ones it supports
797-text chunks, that you can add to the LodePNG_InfoPng with "addText"
798-the color key, if applicable for the given color type
799-the palette, if you encode to a PNG with colorType 3
800-the background color: it'll add a bKGD chunk to the PNG if one is given
801-the interlaceMethod: None (0) or Adam7 (1)
803When encoding to a PNG with colorType 3, the encoder will generate a PLTE chunk.
804If the palette contains any colors for which the alpha channel is not 255 (so
805there are translucent colors in the palette), it'll add a tRNS chunk.
809You specify the color type of the raw image that you give to the input here,
810including a possible transparent color key and palette you happen to be using in
811your raw image data.
813By default, 32-bit color is assumed, meaning your input has to be in RGBA
814format with 4 bytes (unsigned chars) per pixel.
818The following settings are supported (some are in sub-structs):
819*) autoLeaveOutAlphaChannel: when this option is enabled, when you specify a PNG
820color type with alpha channel (not to be confused with the color type of the raw
821image you specify!!), but the encoder detects that all pixels of the given image
822are opaque, then it'll automatically use the corresponding type without alpha
823channel, resulting in a smaller PNG image.
824*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree, 2 = dynamic huffman tree (best compression)
825*) useLZ77: whether or not to use LZ77 for compressed block types
826*) windowSize: the window size used by the LZ77 encoder (1 - 32768)
827*) force_palette: if colorType is 2 or 6, you can make the encoder write a PLTE
828 chunk if force_palette is true. This can used as suggested palette to convert
829 to by viewers that don't support more than 256 colors (if those still exist)
830*) add_id: add text chunk "Encoder: LodePNG <version>" to the image.
831*) text_compression: default 0. If 1, it'll store texts as zTXt instead of tEXt chunks.
832 zTXt chunks use zlib compression on the text. This gives a smaller result on
833 large texts but a larger result on small texts (such as a single program name).
834 It's all tEXt or all zTXt though, there's no separate setting per text yet.
8377. color conversions
840For trickier usage of LodePNG, you need to understand about PNG color types and
841about how and when LodePNG uses the settings in LodePNG_InfoPng, LodePNG_InfoRaw and Settings.
843=PNG color types=
845A PNG image can have many color types, ranging from 1-bit color to 64-bit color,
846as well as palettized color modes. After the zlib decompression and unfiltering
847in the PNG image is done, the raw pixel data will have that color type and thus
848a certain amount of bits per pixel. If you want the output raw image after
849decoding to have another color type, a conversion is done by LodePNG.
851The PNG specification mentions the following color types:
8530: greyscale, bit depths 1, 2, 4, 8, 16
8542: RGB, bit depths 8 and 16
8553: palette, bit depths 1, 2, 4 and 8
8564: greyscale with alpha, bit depths 8 and 16
8576: RGBA, bit depths 8 and 16
859Bit depth is the amount of bits per color channel.
861=Default Behaviour of LodePNG=
863By default, the Decoder will convert the data from the PNG to 32-bit RGBA color,
864no matter what color type the PNG has, so that the result can be used directly
865as a texture in OpenGL etc... without worries about what color type the original
866image has.
868The Encoder assumes by default that the raw input you give it is a 32-bit RGBA
869buffer and will store the PNG as either 32 bit or 24 bit depending on whether
870or not any translucent pixels were detected in it.
872To get the default behaviour, don't change the values of LodePNG_InfoRaw and LodePNG_InfoPng of
873the encoder, and don't change the values of LodePNG_InfoRaw of the decoder.
875=Color Conversions=
877As explained in the sections about the Encoder and Decoder, you can specify
878color types and bit depths in LodePNG_InfoPng and LodePNG_InfoRaw, to change the default behaviour
879explained above. (for the Decoder you can only specify the LodePNG_InfoRaw, because the
880LodePNG_InfoPng contains what the PNG file has).
882To avoid some confusion:
883-the Decoder converts from PNG to raw image
884-the Encoder converts from raw image to PNG
885-the color type and bit depth in LodePNG_InfoRaw, are those of the raw image
886-the color type and bit depth in LodePNG_InfoPng, are those of the PNG
887-if the color type of the LodePNG_InfoRaw and PNG image aren't the same, a conversion
888between the color types is done if the color types are supported
890Supported color types:
891-It's possible to load PNGs from any colortype and to save PNGs of any colorType.
892-Both encoder and decoder use the same converter. So both encoder and decoder
893suport the same color types at the input and the output. So the decoder supports
894any type of PNG image and can convert it to certain types of raw image, while the
895encoder supports any type of raw data but only certain color types for the output PNG.
896-The converter can convert from _any_ input color type, to 24-bit RGB or 32-bit RGBA
897-The converter can convert from greyscale input color type, to 8-bit greyscale or greyscale with alpha
898-If both color types are the same, conversion from anything to anything is possible
899-Color types that are invalid according to the PNG specification are not allowed
900-When converting from a type with alpha channel to one without, the alpha channel information is discarded
901-When converting from a type without alpha channel to one with, the result will be opaque except pixels that have the same color as the color key of the input if one was given
902-When converting from 16-bit bitDepth to 8-bit bitDepth, the 16-bit precision information is lost, only the most significant byte is kept
903-Converting from color to greyscale is not supported on purpose: choosing what kind of color to greyscale conversion to do is not a decision a PNG codec should make
904-Converting from/to a palette type, only keeps the indices, it ignores the colors defined in the palette
906No conversion needed...:
907-If the color type of the PNG image and raw image are the same, then no
908conversion is done, and all color types are supported.
909-In the encoder, you can make it save a PNG with any color by giving the
910LodePNG_InfoRaw and LodePNG_InfoPng the same color type.
911-In the decoder, you can make it store the pixel data in the same color type
912as the PNG has, by setting the color_convert setting to false. Settings in
913infoRaw are then ignored.
915The function LodePNG_convert does this, which is available in the interface but
916normally isn't needed since the encoder and decoder already call it.
918=More Notes=
920In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines
921have a bit amount that isn't a multiple of 8, then padding bits are used so that each
922scanline starts at a fresh byte.
923However: The input image you give to the encoder, and the output image you get from the decoder
924will NOT have these padding bits in that case, e.g. in the case of a 1-bit image with a width
925of 7 pixels, the first pixel of the second scanline will the the 8th bit of the first byte,
926not the first bit of a new byte.
9288. info values
931Both the encoder and decoder use a variable of type LodePNG_InfoPng and LodePNG_InfoRaw, which
932both also contain a LodePNG_InfoColor. Here's a list of each of the values stored in them:
934*) info from the PNG header (IHDR chunk):
936width: width of the image in pixels
937height: height of the image in pixels
938colorType: color type of the original PNG file
939bitDepth: bits per sample
940compressionMethod: compression method of the original file. Always 0.
941filterMethod: filter method of the original file. Always 0.
942interlaceMethod: interlace method of the original file. 0 is no interlace, 1 is adam7 interlace.
944Note: width and height are only used as information of a decoded PNG image. When encoding one, you don't have
945to specify width and height in an LodePNG_Info struct, but you give them as parameters of the encode function.
946The rest of the LodePNG_Info struct IS used by the encoder though!
948*) palette:
950This is a dynamically allocated unsigned char array with the colors of the palette. The value palettesize
951indicates the amount of colors in the palette. The allocated size of the buffer is 4 * palettesize bytes,
952because there are 4 values per color: R, G, B and A. Even if less color channels are used, the palette
953is always in RGBA format, in the order RGBARGBARGBA.....
955When encoding a PNG, to store your colors in the palette of the LodePNG_InfoRaw, first use
956LodePNG_InfoColor_clearPalette, then for each color use LodePNG_InfoColor_addPalette.
957In the C++ version the Encoder class also has the above functions available directly in its interface.
959Note that the palette information from the tRNS chunk is also already included in this palette vector.
961If you encode an image with palette, don't forget that you have to set the alpha channels (A) of the palette
962too, set them to 255 for an opaque palette. If you leave them at zero, the image will be encoded as
963fully invisible. This both for the palette in the infoRaw and the infoPng if the png is to have a palette.
965*) transparent color key
967key_defined: is a transparent color key given?
968key_r: red/greyscale component of color key
969key_g: green component of color key
970key_b: blue component of color key
972For greyscale PNGs, r, g and b will all 3 be set to the same.
974This color is 8-bit for 8-bit PNGs, 16-bit for 16-bit per channel PNGs.
976*) suggested background color
978background_defined: is a suggested background color given?
979background_r: red component of sugg. background color
980background_g: green component of sugg. background color
981background_b: blue component of sugg. background color
983This color is 8-bit for 8-bit PNGs, 16-bit for 16-bit PNGs
985For greyscale PNGs, r, g and b will all 3 be set to the same. When encoding
986the encoder writes the red one away.
987For palette PNGs: When decoding, the RGB value will be stored, no a palette
988index. But when encoding, specify the index of the palette in background_r,
989the other two are then ignored.
991The decoder pretty much ignores this background color, after all if you make a
992PNG translucent normally you intend it to be used against any background, on
993websites, as translucent textures in games, ... But you can get the color this
994way if needed.
996*) text and itext
998Non-international text:
1000-text.keys: a char** buffer containing the keywords (see below)
1001-text.strings: a char** buffer containing the texts (see below)
1002-text.num: the amount of texts in the above char** buffers (there may be more texts in itext)
1003-LodePNG_InfoText_clearText: use this to clear the texts again after you filled them in
1004-LodePNG_InfoText_addText: this function is used to push back a keyword and text
1006International text: This is stored in separate arrays! The sum text.num and itext.num is the real amount of texts.
1008-itext.keys: keyword in English
1009-itext.langtags: ISO 639 letter code for the language
1010-itext.transkeys: keyword in this language
1011-itext.strings: the text in this language, in UTF-8
1012-itext.num: the amount of international texts in this PNG
1013-LodePNG_InfoIText_clearText: use this to clear the itexts again after you filled them in
1014-LodePNG_InfoIText_addText: this function is used to push back all 4 parts of an itext
1016Don't allocate these text buffers yourself. Use the init/cleanup functions
1017correctly and use addText and clearText.
1019In the C++ version the Encoder class also has the above functions available directly in its interface.
1020The char** buffers are used like the argv parameter of a main() function, and (i)text.num takes the role
1021of argc.
1023In a text, there must be as much keys as strings because they always form pairs. In an itext,
1024there must always be as much keys, langtags, transkeys and strings.
1026They keyword of text chunks gives a short description what the actual text
1027represents. There are a few standard standard keywords recognised
1028by many programs: Title, Author, Description, Copyright, Creation Time,
1029Software, Disclaimer, Warning, Source, Comment. It's allowed to use other keys.
1031The keyword is minimum 1 character and maximum 79 characters long. It's
1032discouraged to use a single line length longer than 79 characters for texts.
1034*) additional color info
1036These functions are available with longer names in the C version, and directly
1037in the Decoder's interface in the C++ version.
1039getBpp(): bits per pixel of the PNG image
1040getChannels(): amount of color channels of the PNG image
1041isGreyscaleType(): its color type 0 or 4
1042isAlphaType(): its color type 2 or 6
1044These values are calculated out of color type and bit depth of InfoColor.
1046The difference between bits per pixel and bit depth is that bit depth is the
1047number of bits per color channel, while a pixel can have multiple channels.
1049*) pHYs chunk (image dimensions)
1051phys_defined: if 0, there is no pHYs chunk and the values are undefined, if 1 else there is one
1052phys_x: pixels per unit in x direction
1053phys_y: pixels per unit in y direction
1054phys_unit: the unit, 0 is no unit (x and y only give the ratio), 1 is metre
1056*) tIME chunk (modification time)
1058time_defined: if 0, there is no tIME chunk and the values are undefined, if 1 there is one
1059time: this struct contains year as a 2-byte number (0-65535), month, day, hour, minute,
1060second as 1-byte numbers that must be in the correct range
1062Note: to make the encoder add a time chunk, set time_defined to 1 and fill in
1063the correct values in all the time parameters, LodePNG will not fill the current
1064time in these values itself, all it does is copy them over into the chunk bytes.
10679. error values
1070The meanings of the LodePNG error values:
1072*) 0: no error, everything went ok
1073*) 1: the Encoder/Decoder has done nothing yet, so error checking makes no sense yet
1074*) 10: while huffman decoding: end of input memory reached without endcode
1075*) 11: while huffman decoding: error in code tree made it jump outside of tree
1076*) 13: problem while processing dynamic deflate block
1077*) 14: problem while processing dynamic deflate block
1078*) 15: problem while processing dynamic deflate block
1079*) 16: unexisting code while processing dynamic deflate block
1080*) 17: while inflating: end of out buffer memory reached
1081*) 18: while inflating: invalid distance code
1082*) 19: while inflating: end of out buffer memory reached
1083*) 20: invalid deflate block BTYPE encountered while decoding
1084*) 21: NLEN is not ones complement of LEN in a deflate block
1085*) 22: while inflating: end of out buffer memory reached.
1086 This can happen if the inflated deflate data is longer than the amount of bytes required to fill up
1087 all the pixels of the image, given the color depth and image dimensions. Something that doesn't
1088 happen in a normal, well encoded, PNG image.
1089*) 23: while inflating: end of in buffer memory reached
1090*) 24: invalid FCHECK in zlib header
1091*) 25: invalid compression method in zlib header
1092*) 26: FDICT encountered in zlib header while it's not used for PNG
1093*) 27: PNG file is smaller than a PNG header
1094*) 28: incorrect PNG signature (the first 8 bytes of the PNG file)
1095 Maybe it's not a PNG, or a PNG file that got corrupted so that the header indicates the corruption.
1096*) 29: first chunk is not the header chunk
1097*) 30: chunk length too large, chunk broken off at end of file
1098*) 31: illegal PNG color type or bpp
1099*) 32: illegal PNG compression method
1100*) 33: illegal PNG filter method
1101*) 34: illegal PNG interlace method
1102*) 35: chunk length of a chunk is too large or the chunk too small
1103*) 36: illegal PNG filter type encountered
1104*) 37: illegal bit depth for this color type given
1105*) 38: the palette is too big (more than 256 colors)
1106*) 39: more palette alpha values given in tRNS, than there are colors in the palette
1107*) 40: tRNS chunk has wrong size for greyscale image
1108*) 41: tRNS chunk has wrong size for RGB image
1109*) 42: tRNS chunk appeared while it was not allowed for this color type
1110*) 43: bKGD chunk has wrong size for palette image
1111*) 44: bKGD chunk has wrong size for greyscale image
1112*) 45: bKGD chunk has wrong size for RGB image
1113*) 46: value encountered in indexed image is larger than the palette size (bitdepth == 8). Is the palette too small?
1114*) 47: value encountered in indexed image is larger than the palette size (bitdepth < 8). Is the palette too small?
1115*) 48: the input data is empty. Maybe a PNG file you tried to load doesn't exist or is in the wrong path.
1116*) 49: jumped past memory while generating dynamic huffman tree
1117*) 50: jumped past memory while generating dynamic huffman tree
1118*) 51: jumped past memory while inflating huffman block
1119*) 52: jumped past memory while inflating
1120*) 53: size of zlib data too small
1121*) 55: jumped past tree while generating huffman tree, this could be when the
1122 tree will have more leaves than symbols after generating it out of the
1123 given lengths. They call this an oversubscribed dynamic bit lengths tree in zlib.
1124*) 56: given output image colorType or bitDepth not supported for color conversion
1125*) 57: invalid CRC encountered (checking CRC can be disabled)
1126*) 58: invalid ADLER32 encountered (checking ADLER32 can be disabled)
1127*) 59: conversion to unexisting or unsupported color type or bit depth requested by encoder or decoder
1128*) 60: invalid window size given in the settings of the encoder (must be 0-32768)
1129*) 61: invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)
1130*) 62: conversion from non-greyscale color to greyscale color requested by encoder or decoder. LodePNG
1131 leaves the choice of RGB to greyscale conversion formula to the user.
1132*) 63: length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk (2^31-1)
1133*) 64: the length of the "end" symbol 256 in the Huffman tree is 0, resulting in the inability of a deflated
1134 block to ever contain an end code. It must be at least 1.
1135*) 66: the length of a text chunk keyword given to the encoder is longer than the maximum 79 bytes.
1136*) 67: the length of a text chunk keyword given to the encoder is smaller than the minimum 1 byte.
1137*) 68: tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors
1138*) 69: unknown chunk type with "critical" flag encountered by the decoder
1139*) 71: unexisting interlace mode given to encoder (must be 0 or 1)
1140*) 72: while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)
1141*) 73: invalid tIME chunk size
1142*) 74: invalid pHYs chunk size
1143*) 75: no null termination char found while decoding any kind of text chunk, or wrong length
1144*) 76: iTXt chunk too short to contain required bytes
1145*) 77: integer overflow in buffer size happened somewhere
1146*) 78: file doesn't exist or couldn't be opened for reading
1147*) 79: file couldn't be opened for writing
1148*) 80: tried creating a tree for 0 symbols
1149*) 9900-9999: out of memory while allocating chunk of memory somewhere
115210. file IO
1155For cases where you want to load the PNG image from a file, you can use your own
1156file loading code, or the file loading and saving functions provided with
1157LodePNG. These use the same unsigned char format used by the Decoder and Encoder.
1159The loadFile function fills the given buffer up with the file from harddisk
1160with the given name.
1162The saveFile function saves the contents of the given buffer to the file
1163with given name. Warning: this overwrites the contents that were previously in
1164the file if it already existed, without warning.
1166Note that you don't have to decode a PNG image from a file, you can as well
1167retrieve the buffer another way in your code, because the decode function takes
1168a buffer as parameter, not a filename.
1170Both C and C++ versions of the loadFile and saveFile functions are available.
1171For the C version of loadFile, you need to free() the buffer after use. The
1172C++ versions use std::vectors so they clean themselves automatically.
117511. chunks and PNG editing
1178If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG
1179editor that should follow the rules about handling of unknown chunks, or if you
1180program is able to read other types of chunks than the ones handled by LodePNG,
1181then that's possible with the chunk functions of LodePNG.
1183A PNG chunk has the following layout:
11854 bytes length
11864 bytes type name
1187length bytes data
11884 bytes CRC
119111.1 iterating through chunks
1194If you have a buffer containing the PNG image data, then the first chunk (the
1195IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the
1196signature of the PNG and are not part of a chunk. But if you start at byte 8
1197then you have a chunk, and can check the following things of it.
1199NOTE: none of these functions check for memory buffer boundaries. To avoid
1200exploits, always make sure the buffer contains all the data of the chunks.
1201When using LodePNG_chunk_next, make sure the returned value is within the
1202allocated memory.
1204unsigned LodePNG_chunk_length(const unsigned char* chunk):
1206Get the length of the chunk's data. The total chunk length is this length + 12.
1208void LodePNG_chunk_type(char type[5], const unsigned char* chunk):
1209unsigned char LodePNG_chunk_type_equals(const unsigned char* chunk, const char* type):
1211Get the type of the chunk or compare if it's a certain type
1213unsigned char LodePNG_chunk_critical(const unsigned char* chunk):
1214unsigned char LodePNG_chunk_private(const unsigned char* chunk):
1215unsigned char LodePNG_chunk_safetocopy(const unsigned char* chunk):
1217Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are).
1218Check if the chunk is private (public chunks are part of the standard, private ones not).
1219Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical
1220chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your
1221program doesn't handle that type of unknown chunk.
1223unsigned char* LodePNG_chunk_data(unsigned char* chunk):
1224const unsigned char* LodePNG_chunk_data_const(const unsigned char* chunk):
1226Get a pointer to the start of the data of the chunk.
1228unsigned LodePNG_chunk_check_crc(const unsigned char* chunk):
1229void LodePNG_chunk_generate_crc(unsigned char* chunk):
1231Check if the crc is correct or generate a correct one.
1233unsigned char* LodePNG_chunk_next(unsigned char* chunk):
1234const unsigned char* LodePNG_chunk_next_const(const unsigned char* chunk):
1236Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these
1237functions do no boundary checking of the allocated data whatsoever, so make sure there is enough
1238data available in the buffer to be able to go to the next chunk.
1240unsigned LodePNG_append_chunk(unsigned char** out, size_t* outlength, const unsigned char* chunk):
1241unsigned LodePNG_create_chunk(unsigned char** out, size_t* outlength, unsigned length, const char* type, const unsigned char* data):
1243These functions are used to create new chunks that are appended to the data in *out that has
1244length *outlength. The append function appends an existing chunk to the new data. The create
1245function creates a new chunk with the given parameters and appends it. Type is the 4-letter
1246name of the chunk.
124911.2 chunks in infoPng
1252The LodePNG_InfoPng struct contains a struct LodePNG_UnknownChunks in it. This
1253struct has 3 buffers (each with size) to contain 3 types of unknown chunks:
1254the ones that come before the PLTE chunk, the ones that come between the PLTE
1255and the IDAT chunks, and the ones that come after the IDAT chunks.
1256It's necessary to make the distionction between these 3 cases because the PNG
1257standard forces to keep the ordering of unknown chunks compared to the critical
1258chunks, but does not force any other ordering rules.
1259[0] is the chunks before PLTE[1] is the chunks after PLTE, before IDAT[2] is the chunks after IDAT
1264The chunks in these 3 buffers can be iterated through and read by using the same
1265way described in the previous subchapter.
1267When using the decoder to decode a PNG, you can make it store all unknown chunks
1268if you set the option settings.rememberUnknownChunks to 1. By default, this option
1269is off and is 0.
1271The encoder will always encode unknown chunks that are stored in the infoPng. If
1272you need it to add a particular chunk that isn't known by LodePNG, you can use
1273LodePNG_append_chunk or LodePNG_create_chunk to the chunk data in[x].
1276Chunks that are known by LodePNG should not be added in that way. E.g. to make
1277LodePNG add a bKGD chunk, set background_defined to true and add the correct
1278parameters there and LodePNG will generate the chunk.
128112. compiler support
1284No libraries other than the current standard C library are needed to compile
1285LodePNG. For the C++ version, only the standard C++ library is needed on top.
1286Add the files lodepng.c(pp) and lodepng.h to your project, include
1287lodepng.h where needed, and your program can read/write PNG files.
1289Use optimization! For both the encoder and decoder, compiling with the best
1290optimizations makes a large difference.
1292Make sure that LodePNG is compiled with the same compiler of the same version
1293and with the same settings as the rest of the program, or the interfaces with
1294std::vectors and std::strings in C++ can be incompatible resulting in bad things.
1296CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets.
1298*) gcc and g++
1300LodePNG is developed in gcc so this compiler is natively supported. It gives no
1301warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++
1302version 4.2.2 on Linux.
1304*) Mingw and Bloodshed DevC++
1306The Mingw compiler (a port of gcc) used by Bloodshed DevC++ for Windows is fully
1307supported by LodePNG.
1309*) Visual Studio 2005 and Visual C++ 2005 Express Edition
1311Versions 20070604 up to 20080107 have been tested on VS2005 and work. There are no
1312warnings, except two warnings about 'fopen' being deprecated. 'fopen' is a function
1313required by the C standard, so this warning is the fault of VS2005, it's nice of
1314them to enforce secure code, however the multiplatform LodePNG can't follow their
1315non-standard extensions. LodePNG is fully ISO C90 compliant.
1317If you're using LodePNG in VS2005 and don't want to see the deprecated warnings,
1318put this on top of lodepng.h before the inclusions: #define _CRT_SECURE_NO_DEPRECATE
1320*) Visual Studio 6.0
1322The C++ version of LodePNG was not supported by Visual Studio 6.0 because Visual
1323Studio 6.0 doesn't follow the C++ standard and implements it incorrectly.
1324The current C version of LodePNG has not been tested in VS6 but may work now.
1326*) Comeau C/C++
1328Vesion 20070107 compiles without problems on the Comeau C/C++ Online Test Drive
1329at in both C90 and C++ mode.
1331*) Compilers on Macintosh
1333I'd love to support Macintosh but don't have one available to test it on.
1334If it doesn't work with your compiler, maybe it can be gotten to work with the
1335gcc compiler for Macintosh. Someone reported that it doesn't work well at all
1336for Macintosh. All information on attempts to get it to work on Mac is welcome.
1338*) Other Compilers
1340If you encounter problems on other compilers, I'm happy to help out make LodePNG
1341support the compiler if it supports the ISO C90 and C++ standard well enough. If
1342the required modification to support the compiler requires using non standard or
1343lesser C/C++ code or headers, I won't support it.
134613. examples
1349This decoder and encoder example show the most basic usage of LodePNG (using the
1350classes, not the simple functions, which would be trivial)
1352More complex examples can be found in:
1353-lodepng_examples.c: 9 different examples in C, such as showing the image with SDL, ...
1354-lodepng_examples.cpp: the exact same examples in C++ using the C++ wrapper of LodePNG
135713.1. decoder C++ example
1361#include "lodepng.h"
1362#include <iostream>
1364int main(int argc, char *argv[])
1366 const char* filename = argc > 1 ? argv[1] : "test.png";
1368 //load and decode
1369 std::vector<unsigned char> buffer, image;
1370 LodePNG::loadFile(buffer, filename); //load the image file with given filename
1371 LodePNG::Decoder decoder;
1372 decoder.decode(image, buffer.size() ? &buffer[0] : 0, (unsigned)buffer.size()); //decode the png
1374 //if there's an error, display it
1375 if(decoder.hasError()) std::cout << "error: " << decoder.getError() << std::endl;
1377 //the pixels are now in the vector "image", use it as texture, draw it, ...
1380//alternative version using the "simple" function
1381int main(int argc, char *argv[])
1383 const char* filename = argc > 1 ? argv[1] : "test.png";
1385 //load and decode
1386 std::vector<unsigned char> image;
1387 unsigned w, h;
1388 unsigned error = LodePNG::decode(image, w, h, filename);
1390 //if there's an error, display it
1391 if(error != 0) std::cout << "error: " << error << std::endl;
1393 //the pixels are now in the vector "image", use it as texture, draw it, ...
139813.2 encoder C++ example
1402#include "lodepng.h"
1403#include <iostream>
1405int main(int argc, char *argv[])
1407 //check if user gave a filename
1408 if(argc <= 1)
1409 {
1410 std::cout << "please provide a filename to save to\n";
1411 return 0;
1412 }
1414 //generate some image
1415 std::vector<unsigned char> image;
1416 image.resize(512 * 512 * 4);
1417 for(unsigned y = 0; y < 512; y++)
1418 for(unsigned x = 0; x < 512; x++)
1419 {
1420 image[4 * 512 * y + 4 * x + 0] = 255 * !(x & y);
1421 image[4 * 512 * y + 4 * x + 1] = x ^ y;
1422 image[4 * 512 * y + 4 * x + 2] = x | y;
1423 image[4 * 512 * y + 4 * x + 3] = 255;
1424 }
1426 //encode and save
1427 std::vector<unsigned char> buffer;
1428 LodePNG::Encoder encoder;
1429 encoder.encode(buffer, image, 512, 512);
1430 LodePNG::saveFile(buffer, argv[1]);
1432 //the same as the 4 lines of code above, but in 1 call:
1433 //LodePNG::encode(argv[1], image, 512, 512);
143813.3 Decoder C example
1441This example loads the PNG in 1 function call
1443#include "lodepng.h"
1445int main(int argc, char *argv[])
1447 unsigned error;
1448 unsigned char* image;
1449 size_t w, h;
1451 if(argc <= 1) return 0;
1453 error = LodePNG_decode3(&image, &w, &h, filename);
1455 free(image);
145914. LodeZlib
1462Also available in the interface is LodeZlib. Both C and C++ versions of these
1463functions are available. The interface is similar to that of the "simple" PNG
1464encoding and decoding functions.
1466LodeZlib can be used to zlib compress and decompress a buffer. It cannot be
1467used to create gzip files however. Also, it only supports the part of zlib
1468that is required for PNG, it does not support compression and decompression
1469with dictionaries.
147215. changes
1475The version number of LodePNG is the date of the change given in the format
1478Some changes aren't backwards compatible. Those are indicated with a (!)
1481*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could
1482 read by ignoring the problem but windows apps couldn't.
1483*) 06 jun 2008: added more error checks for out of memory cases.
1484*) 26 apr 2008: added a few more checks here and there to ensure more safety.
1485*) 06 mar 2008: crash with encoding of strings fixed
1486*) 02 feb 2008: support for international text chunks added (iTXt)
1487*) 23 jan 2008: small cleanups, and #defines to divide code in sections
1488*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor.
1489*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder.
1490*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added
1491 Also vareous fixes, such as in the deflate and the padding bits code.
1492*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved
1493 filtering code of encoder.
1494*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A
1495 C++ wrapper around this provides an interface almost identical to before.
1496 Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code
1497 are together in these files but it works both for C and C++ compilers.
1498*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks
1499*) 30 aug 2007: bug fixed which makes this Borland C++ compatible
1500*) 09 aug 2007: some VS2005 warnings removed again
1501*) 21 jul 2007: deflate code placed in new namespace separate from zlib code
1502*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images
1503*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing
1504 invalid std::vector element [0] fixed, and level 3 and 4 warnings removed
1505*) 02 jun 2007: made the encoder add a tag with version by default
1506*) 27 may 2007: zlib and png code separated (but still in the same file),
1507 simple encoder/decoder functions added for more simple usage cases
1508*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69),
1509 moved some examples from here to lodepng_examples.cpp
1510*) 12 may 2007: palette decoding bug fixed
1511*) 24 apr 2007: changed the license from BSD to the zlib license
1512*) 11 mar 2007: very simple addition: ability to encode bKGD chunks.
1513*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding
1514 palettized PNG images. Plus little interface change with palette and texts.
1515*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes.
1516 Fixed a bug where the end code of a block had length 0 in the Huffman tree.
1517*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented
1518 and supported by the encoder, resulting in smaller PNGs at the output.
1519*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone.
1520*) 24 jan 2007: gave encoder an error interface. Added color conversion from any
1521 greyscale type to 8-bit greyscale with or without alpha.
1522*) 21 jan 2007: (!) Totally changed the interface. It allows more color types
1523 to convert to and is more uniform. See the manual for how it works now.
1524*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days:
1525 encode/decode custom tEXt chunks, separate classes for zlib & deflate, and
1526 at last made the decoder give errors for incorrect Adler32 or Crc.
1527*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel.
1528*) 29 dec 2006: Added support for encoding images without alpha channel, and
1529 cleaned out code as well as making certain parts faster.
1530*) 28 dec 2006: Added "Settings" to the encoder.
1531*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now.
1532 Removed some code duplication in the decoder. Fixed little bug in an example.
1533*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter.
1534 Fixed a bug of the decoder with 16-bit per color.
1535*) 15 okt 2006: Changed documentation structure
1536*) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the
1537 given image buffer, however for now it's not compressed.
1538*) 08 sep 2006: (!) Changed to interface with a Decoder class
1539*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different
1540 way. Renamed decodePNG to decodePNGGeneric.
1541*) 29 jul 2006: (!) Changed the interface: image info is now returned as a
1542 struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy.
1543*) 28 jul 2006: Cleaned the code and added new error checks.
1544 Corrected terminology "deflate" into "inflate".
1545*) 23 jun 2006: Added SDL example in the documentation in the header, this
1546 example allows easy debugging by displaying the PNG and its transparency.
1547*) 22 jun 2006: (!) Changed way to obtain error value. Added
1548 loadFile function for convenience. Made decodePNG32 faster.
1549*) 21 jun 2006: (!) Changed type of info vector to unsigned.
1550 Changed position of palette in info vector. Fixed an important bug that
1551 happened on PNGs with an uncompressed block.
1552*) 16 jun 2006: Internally changed unsigned into unsigned where
1553 needed, and performed some optimizations.
1554*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them
1555 in LodePNG namespace. Changed the order of the parameters. Rewrote the
1556 documentation in the header. Renamed files to lodepng.cpp and lodepng.h
1557*) 22 apr 2006: Optimized and improved some code
1558*) 07 sep 2005: (!) Changed to std::vector interface
1559*) 12 aug 2005: Initial release
156216. contact information
1565Feel free to contact me with suggestions, problems, comments, ... concerning
1566LodePNG. If you encounter a PNG image that doesn't work properly with this
1567decoder, feel free to send it and I'll use it to find and fix the problem.
1569My email address is (puzzle the account and domain together with an @ symbol):
1570Domain: gmail dot com.
1571Account: lode dot vandevenne.
1574Copyright (c) 2005-2008 Lode Vandevenne

Archive Download this file

Revision: 1322