📄 libpng.3
字号:
will also want to insure that you are, in fact, dealing with a PNGfile. Libpng provides a simple check to see if a file is a PNG file.To use it, pass in the first 1 to 8 bytes of the file to the functionpng_sig_cmp(), and it will return 0 if the bytes match the correspondingbytes of the PNG signature, or nonzero otherwise. Of course, the more bytesyou pass in, the greater the accuracy of the prediction.If you are intending to keep the file pointer open for use in libpng,you must ensure you don't read more than 8 bytes from the beginningof the file, and you also have to make a call to png_set_sig_bytes_read()with the number of bytes you read from the beginning. Libpng willthen only check the bytes (if any) that your program didn't read.(*): If you are not using the standard I/O functions, you will needto replace them with custom functions. See the discussion underCustomizing libpng. FILE *fp = fopen(file_name, "rb"); if (!fp) { return (ERROR); } fread(header, 1, number, fp); is_png = !png_sig_cmp(header, 0, number); if (!is_png) { return (NOT_PNG); }Next, png_struct and png_info need to be allocated and initialized. Inorder to ensure that the size of these structures is correct even with adynamically linked libpng, there are functions to initialize andallocate the structures. We also pass the library version, optionalpointers to error handling functions, and a pointer to a data struct foruse by the error functions, if necessary (the pointer and functions canbe NULL if the default error handlers are to be used). See the sectionon Changes to Libpng below regarding the old initialization functions.The structure allocation functions quietly return NULL if they fail tocreate the structure, so your application should check for that. png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr, user_error_fn, user_warning_fn); if (!png_ptr) return (ERROR); png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); return (ERROR); } png_infop end_info = png_create_info_struct(png_ptr); if (!end_info) { png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL); return (ERROR); }If you want to use your own memory allocation routines,define PNG_USER_MEM_SUPPORTED and usepng_create_read_struct_2() instead of png_create_read_struct(): png_structp png_ptr = png_create_read_struct_2 (PNG_LIBPNG_VER_STRING, (png_voidp)user_error_ptr, user_error_fn, user_warning_fn, (png_voidp) user_mem_ptr, user_malloc_fn, user_free_fn);The error handling routines passed to png_create_read_struct()and the memory alloc/free routines passed to png_create_struct_2()are only necessary if you are not using the libpng supplied errorhandling and memory alloc/free functions.When libpng encounters an error, it expects to longjmp backto your routine. Therefore, you will need to call setjmp and passyour png_jmpbuf(png_ptr). If you read the file from differentroutines, you will need to update the jmpbuf field every time you entera new routine that will call a png_*() function.See your documentation of setjmp/longjmp for your compiler for moreinformation on setjmp/longjmp. See the discussion on libpng errorhandling in the Customizing Libpng section below for more informationon the libpng error handling. If an error occurs, and libpng longjmp'sback to your setjmp, you will want to call png_destroy_read_struct() tofree any memory. if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); fclose(fp); return (ERROR); }If you would rather avoid the complexity of setjmp/longjmp issues,you can compile libpng with PNG_SETJMP_NOT_SUPPORTED, in which caseerrors will result in a call to PNG_ABORT() which defaults to abort().Now you need to set up the input code. The default for libpng is touse the C function fread(). If you use this, you will need to pass avalid FILE * in the function png_init_io(). Be sure that the file isopened in binary mode. If you wish to handle reading data in anotherway, you need not call the png_init_io() function, but you must thenimplement the libpng I/O methods discussed in the Customizing Libpngsection below. png_init_io(png_ptr, fp);If you had previously opened the file and read any of the signature fromthe beginning in order to see if this was a PNG file, you need to letlibpng know that there are some bytes missing from the start of the file. png_set_sig_bytes(png_ptr, number);.SS Setting up callback codeYou can set up a callback function to handle any unknown chunks in theinput stream. You must supply the function read_chunk_callback(png_ptr ptr, png_unknown_chunkp chunk); { /* The unknown chunk structure contains your chunk data: */ png_byte name[5]; png_byte *data; png_size_t size; /* Note that libpng has already taken care of the CRC handling */ /* put your code here. Return one of the following: */ return (-n); /* chunk had an error */ return (0); /* did not recognize */ return (n); /* success */ }(You can give your function another name that you like instead of"read_chunk_callback")To inform libpng about your function, use png_set_read_user_chunk_fn(png_ptr, user_chunk_ptr, read_chunk_callback);This names not only the callback function, but also a user pointer thatyou can retrieve with png_get_user_chunk_ptr(png_ptr);At this point, you can set up a callback function that will becalled after each row has been read, which you can use to controla progress meter or the like. It's demonstrated in pngtest.c.You must supply a function void read_row_callback(png_ptr ptr, png_uint_32 row, int pass); { /* put your code here */ }(You can give it another name that you like instead of "read_row_callback")To inform libpng about your function, use png_set_read_status_fn(png_ptr, read_row_callback);.SS Width and height limitsThe PNG specification allows the width and height of an image to be aslarge as 2^31-1 (0x7fffffff), or about 2.147 billion rows and columns.Since very few applications really need to process such large images,we have imposed an arbitrary 1-million limit on rows and columns.Larger images will be rejected immediately with a png_error() call. Ifyou wish to override this limit, you can use png_set_user_limits(png_ptr, width_max, height_max);to set your own limits, or use width_max = height_max = 0x7fffffffLto allow all valid dimensions (libpng may reject some very large imagesanyway because of potential buffer overflow conditions).You should put this statement after you create the PNG structure andbefore calling png_read_info(), png_read_png(), or png_process_data().If you need to retrieve the limits that are being applied, use width_max = png_get_user_width_max(png_ptr); height_max = png_get_user_height_max(png_ptr);.SS Unknown-chunk handlingNow you get to set the way the library processes unknown chunks in theinput PNG stream. Both known and unknown chunks will be read. Normalbehavior is that known chunks will be parsed into information invarious info_ptr members; unknown chunks will be discarded. To changethis, you can call: png_set_keep_unknown_chunks(png_ptr, keep, chunk_list, num_chunks); keep - 0: do not handle as unknown 1: do not keep 2: keep only if safe-to-copy 3: keep even if unsafe-to-copy You can use these definitions: PNG_HANDLE_CHUNK_AS_DEFAULT 0 PNG_HANDLE_CHUNK_NEVER 1 PNG_HANDLE_CHUNK_IF_SAFE 2 PNG_HANDLE_CHUNK_ALWAYS 3 chunk_list - list of chunks affected (a byte string, five bytes per chunk, NULL or '\0' if num_chunks is 0) num_chunks - number of chunks affected; if 0, all unknown chunks are affected. If nonzero, only the chunks in the list are affectedUnknown chunks declared in this way will be saved as raw data onto alist of png_unknown_chunk structures. If a chunk that is normallyknown to libpng is named in the list, it will be handled as unknown,according to the "keep" directive. If a chunk is named in successiveinstances of png_set_keep_unknown_chunks(), the final instance willtake precedence. The IHDR and IEND chunks should not be named inchunk_list; if they are, libpng will process them normally anyway..SS The high-level read interfaceAt this point there are two ways to proceed; through the high-levelread interface, or through a sequence of low-level read operations.You can use the high-level interface if (a) you are willing to readthe entire image into memory, and (b) the input transformationsyou want to do are limited to the following set: PNG_TRANSFORM_IDENTITY No transformation PNG_TRANSFORM_STRIP_16 Strip 16-bit samples to 8 bits PNG_TRANSFORM_STRIP_ALPHA Discard the alpha channel PNG_TRANSFORM_PACKING Expand 1, 2 and 4-bit samples to bytes PNG_TRANSFORM_PACKSWAP Change order of packed pixels to LSB first PNG_TRANSFORM_EXPAND Perform set_expand() PNG_TRANSFORM_INVERT_MONO Invert monochrome images PNG_TRANSFORM_SHIFT Normalize pixels to the sBIT depth PNG_TRANSFORM_BGR Flip RGB to BGR, RGBA to BGRA PNG_TRANSFORM_SWAP_ALPHA Flip RGBA to ARGB or GA to AG PNG_TRANSFORM_INVERT_ALPHA Change alpha from opacity to transparency PNG_TRANSFORM_SWAP_ENDIAN Byte-swap 16-bit samples(This excludes setting a background color, doing gamma transformation,dithering, and setting filler.) If this is the case, simply do this: png_read_png(png_ptr, info_ptr, png_transforms, NULL)where png_transforms is an integer containing the bitwise OR ofsome set of transformation flags. This call is equivalent to png_read_info(),followed the set of transformations indicated by the transform mask,then png_read_image(), and finally png_read_end().(The final parameter of this call is not yet used. Someday it might pointto transformation parameters required by some future input transform.)You must use png_transforms and not call any png_set_transform() functionswhen you use png_read_png().
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -