Reading and Writing PNG files

Source: Internet
Author: User

I recently studied how to read and write PNG files. I will share my experiences with you.

PNG is an image file storage format developed in the middle of 1990s. It aims to replace GIF and TIFF file formats and add features not available in GIF file formats. The portable network graphic format (PNG) name is derived from the unofficial "PNG's not GIF". It is a bitmap file storage format, read as "ping ". When PNG is used to store a grayscale image, the depth of the grayscale image can be up to 16 bits. When the color image is stored, the depth of the color image can be up to 48 bits, it can also store up to 16-bit alpha channel data. PNG uses the lossless data compression algorithm derived from lz77.

PNG format. This is not detailed here. You can search for it on the Internet.

A png Image Format File (or data stream) consists of an 8-byte PNG file signature domain and more than three chunks organized according to a specific structure. PNG defines two types of data blocks. One is critical chunk, which is a standard data block, and the other is ancillary chunks ), this is an optional data block. Key data blocks define four standard data blocks. Each PNG file must contain them. PNG read/write software must also support these data blocks. Although the PNG file specification does not require the PNG encoding/Decoding of optional data blocks, the specification advocates the support of optional data blocks.

We are concerned about how to complete the requirements of the boss in the shortest time to implement the reading and writing operations of PNG files because the PNG format is so troublesome. I promise that after reading my article, you will be able to compile the program in less than half a day and deliver the program to your boss with satisfaction.

Now, let's get down to the truth. How do I read and write PNG files?

Libpng is a free and open source library that supports operations such as creating, reading, and writing PNG graphics files. You can download the source code from www.libpng.org. Libpng uses the zlib library as the compression engine, and zlib is also a well-known gzip (GNU zip) compression engine. Zlib is a common compression library that provides a set of In-memory compression and decompression functions, and can detect the integrity of extracted data (integrity ). Zlib also supports reading and writing gzip (.gz) files. These files are free and public.

After pbglib is downloaded and zlib is downloaded, how can it be added to the code? Take vc6. as an example. The same is true for other cbuild compilers.

For example, we downloaded an lpng1210.zipand zlib-1.2.3.tar.tar from the Internet. First decompress them. Find projects/visualc6/LibPNG. DSW in the lpng directory. And find zlib-1.2.3/projects/visualc6/zlib. DSW in zlib.

Use VC to open the libpng project file and add the zlib project file. Set the output paths of zlib. lib and PBG. Lib set in setting, and include paths (this simple method is understandable ). After running, two static databases are generated.

After Lib is completed, we can add lib to the project we want to do. Set in link and add PNG. h and zlib. h. In this way, you can officially use libpng! You can also refer to a post about the internet diary that loves blue sky.

The following will be the key content. How to Use pnglib to read and write files? Let's open a example. C. comment under pnglib and write it clearly.

/* Read a PNG file. You may want to return an error code if the read
* Fails (depending upon the failure). There are two "prototypes" given
* Here-one where we are given the filename, and we need to open
* File, and the other where we are given an open file (possibly
* Some or all of the magic bytes read-see comments above ).
*/
# Ifdef open_file/* prototype 1 */
Void read_png (char * file_name)/* we need to open the file */
{
Define two very important pngwen file pointers. Png_info contains pngchuck and PNG data.

Png_structp png_ptr;
Png_infop info_ptr;

These are the parameters required to read the image, and the Image Height. Width, depth, image type, and staggered type.
Unsigned int sig_read = 0;
Png_uint_32 width, height;
Int bit_depth, color_type, interlace_type;
File * FP;

Open the file and give the file pointer to png_prt.
If (FP = fopen (file_name, "rb") = NULL)
Return (error );
# Else no_open_file/* Prototype 2 */
Void read_png (File * FP, unsigned int sig_read)/* file is already open */
{
Png_structp png_ptr;
Png_infop info_ptr;
Png_uint_32 width, height;
Int bit_depth, color_type, interlace_type;
# Endif no_open_file/* only use one prototype! */

/* Create and initialize the png_struct with the desired error handler
* Functions. If you want to use the default stderr and longjump method,
* You can supply NULL for the last three parameters. We also supply
* The Compiler header file version, so that we know if the application
* Was compiled with a compatible version of the library. Required
*/
Png_ptr = png_create_read_struct (png_libpng_ver_string,
Png_voidp user_error_ptr, user_error_fn, user_warning_fn );

If (png_ptr = NULL)
{
Fclose (FP );
Return (error );
}

/* Allocate/initialize the memory for image information. required .*/
Info_ptr = png_create_info_struct (png_ptr );
If (info_ptr = NULL)
{
Fclose (FP );
Png_destroy_read_struct (& png_ptr, png_infopp_null, png_infopp_null );
Return (error );
}

/* Set error handling if you are using the setjmp/longjmp method (this is
* The normal method of doing things with libpng). required unless you
* Set up your own error handlers in the png_create_read_struct () earlier.
*/

If (setjmp (png_jmpbuf (png_ptr )))
{
/* Free all of the memory associated with the png_ptr and info_ptr */
Png_destroy_read_struct (& png_ptr, & info_ptr, png_infopp_null );
Fclose (FP );
/* If we get here, we had a problem reading the file */
Return (error );
}

/* One of the following I/O initialization methods is required */
# Ifdef streams/* PNG file I/O Method 1 */
/* Set up the input control if you are using standard C streams */
Png_init_io (png_ptr, FP );

# Else no_streams/* PNG file I/O method 2 */
/* If you are using replacement read functions, instead of calling
* Png_init_io () Here you wowould call:
*/
Png_set_read_fn (png_ptr, (void *) user_io_ptr, user_read_fn );
/* Where user_io_ptr is a structure you want available to the callbacks */
# Endif no_streams/* use only one I/O method! */

/* If we have already read some of the signature */
Png_set_sig_bytes (png_ptr, sig_read );

# Ifdef hilevel
/*
* If you have enough memory to read in the entire image at once,
* And you need to specify only transforms that can be controlled
* With One Of The png_transform _ * bits (This presently excludes
* Dithering, filling, setting background, and doing Gamma
* Adjustment), then you can read the entire image (including
* Pixels) into the INFO structure with this call:
*/
Png_read_png (png_ptr, info_ptr, png_transforms, png_voidp_null );
# Else
/* OK, you're doing it the hard way, with the lower-level functions */

/* The call to png_read_info () gives us all of the information from
* PNG file before the first idat (image data chunk). Required
*/
Png_read_info (png_ptr, info_ptr );

Png_get_ihdr (png_ptr, info_ptr, & width, & height, & bit_depth, & color_type,
& Interlace_type, int_p_null, int_p_null );

/* Set up the data transformations you want. Note that these are all
* Optional. Only call them if you want/need them. pointer of
* Transformations only work on specific types of images, and images
* Are mutually exclusive.
*/

/* Tell libpng to strip 16 bit/color files down to 8 bits/color */
Png_set_strip_16 (png_ptr );

/* Strip Alpha bytes from the input data without combining with
* Background (not recommended ).
*/
Png_set_strip_alpha (png_ptr );

/* Extract multiple pixels with bit depths of 1, 2, and 4 from a single
* Byte into separate bytes (useful for paletted and grayscale images ).
*/
Png_set_packing (png_ptr );

/* Change the order of packed pixels to least significant bit first
* (Not useful if you are using png_set_packing ).*/
Png_set_packswap (png_ptr );

/* Expand paletted colors into true RGB triplets */
If (color_type = png_color_type_palette)
Png_set_palette_rgb (png_ptr );

/* Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel */
If (color_type = png_color_type_gray & bit_depth <8)
Png_set_gray_1_2_4_to_8 (png_ptr );

/* Expand paletted or RGB Images with transparency to Full Alpha Channels
* So the data will be available as rgba quartets.
*/
If (png_get_valid (png_ptr, info_ptr, png_info_trns ))
Png_set_trns_to_alpha (png_ptr );

/* Set the background color to draw transparent and Alpha images over.
* It is possible to set the red, green, and blue components directly
* For paletted images instead of supplying a palette index. Note that
* Even if the PNG file supplies a background, you are not required
* Use it-You shoshould use the (solid) application background if it has one.
*/

Png_color_16 my_background, * image_background;

If (png_get_bkgd (png_ptr, info_ptr, & image_background ))
Png_set_background (png_ptr, image_background,
Png_background_gamma_file, 1, 1.0 );
Else
Png_set_background (png_ptr, & my_background,
Png_background_gamma_screen, 0, 1.0 );

/* Some suggestions as to how to get a screen GAMMA value */

/* Note that screen gamma is the display_exponent, which has des
* The crt_exponent and any correction for viewing conditions */
If (/* We have a user-defined screen GAMMA value */)
{
Screen_gamma = User-Defined screen_gamma;
}
/* This is one way that applications share the same screen GAMMA value */
Else if (gamma_str = getenv ("screen_gamma "))! = NULL)
{
Screen_gamma = atof (gamma_str );
}
/* If we don't have another value */
Else
{
Screen_gamma = 2.2;/* a good guess for a PC monitors in a dimly
Living room */
Screen_gamma = 1.7 or 1.0;/* a good guess for MAC systems */
}

/* Tell libpng to handle the Gamma conversion for you. The final call
* Is a good guess for PC generated images, but it shocould be retriable
* By the user at run time by the user. It is stronugly suggested that
* Your application support Gamma Correction.
*/

Int intent;

If (png_get_srgb (png_ptr, info_ptr, & intent ))
Png_set_gamma (png_ptr, screen_gamma, 0.45455 );
Else
{
Double image_gamma;
If (png_get_gama (png_ptr, info_ptr, & image_gamma ))
Png_set_gamma (png_ptr, screen_gamma, image_gamma );
Else
Png_set_gamma (png_ptr, screen_gamma, 0.45455 );
}

/* Dither RGB files down to 8 bit palette or reduce palettes
* To the number of colors available on your screen.
*/
If (color_type & png_color_mask_color)
{
Int num_palette;
Png_colorp palette;

/* This operation CES the image to the application supplied palette */
If (/* we have our own palette */)
{
/* An array of colors to which the image shoshould be dithered */
Png_color std_color_cube [max_screen_colors];

Png_set_dither (png_ptr, std_color_cube, max_screen_colors,
Max_screen_colors, png_uint_16p_null, 0 );
}
/* This operation CES the image to the palette supplied in the file */
Else if (png_get_plte (png_ptr, info_ptr, & palette, & num_palette ))
{
Png_uint_16p histogram = NULL;

Png_get_hist (png_ptr, info_ptr, & histogram );

Png_set_dither (png_ptr, palette, num_palette,
Max_screen_colors, histogram, 0 );
}
}

/* Invert monochrome files to have 0 as white and 1 as black */
Png_set_invert_mono (png_ptr );

/* If you want to shift the pixel values from the range [0,255] or
* [] To the original [] or [], or whatever range
* Colors were originally in:
*/
If (png_get_valid (png_ptr, info_ptr, png_info_sbit ))
{
Png_color_8p sig_bit;

Png_get_sbit (png_ptr, info_ptr, & sig_bit );
Png_set_shift (png_ptr, sig_bit );
}

/* Flip the RGB pixels to BGR (or rgba to bgra )*/
If (color_type & png_color_mask_color)
Png_set_bgr (png_ptr );

/* Swap the rgba or GA data to argb or Ag (or bgra to abgr )*/
Png_set_swap_alpha (png_ptr );

/* Swap bytes of 16 bit files to least significant byte first */
Png_set_swap (png_ptr );

/* Add filler (or alpha) byte (before/after each RGB Triplet )*/
Png_set_filler (png_ptr, 0xff, png_filler_after );

/* Turn On interlace handling. required if you are not using
* Png_read_image (). To see how to handle interlacing passes,
* See the png_read_row () method below:
*/
Number_passes = png_set_interlace_handling (png_ptr );

/* Optional call to Gamma correct and add the background to the palette
* And update INFO structure. required if you are expecting libpng
* Update the palette for you (ie you selected such a transform above ).
*/
Png_read_update_info (png_ptr, info_ptr );

/* Allocate the memory to hold the image using the fields of info_ptr .*/

/* The easiest way to read the image :*/
Png_bytep row_pointers [height];

For (ROW = 0; row {
Row_pointers [row] = png_malloc (png_ptr, png_get_rowbytes (png_ptr,
Info_ptr ));
}

/* Now it's time to read the image. One of these methods is required */
# Ifdef entire/* read the entire image in one go */
Png_read_image (png_ptr, row_pointers );

# Else no_entire/* read the image one or more scanlines at a time */
/* The other way to read images-deal with interlacing :*/

For (pass = 0; pass <number_passes; pass ++)
{
# Ifdef single/* read the image a single row at a time */
For (y = 0; y {
Png_read_rows (png_ptr, & row_pointers [Y], png_bytepp_null, 1 );
}

# Else no_single/* read the image several rows at a time */
For (y = 0; y {
# Ifdef sparkle/* read the image using the "sparkle" effect .*/
Png_read_rows (png_ptr, & row_pointers [Y], png_bytepp_null,
Number_of_rows );
# Else no_sparkle/* read the image using the "rectangle" effect */
Png_read_rows (png_ptr, png_bytepp_null, & row_pointers [Y],
Number_of_rows );
# Endif no_sparkle/* use only one of these two methods */
}

/* If you want to display the image after every pass, do
So here */
# Endif no_single/* use only one of these two methods */
}
# Endif no_entire/* use only one of these two methods */

/* Read rest of file, and get additional chunks in info_ptr-required */
Png_read_end (png_ptr, info_ptr );
# Endif hilevel

/* At this point you have read the entire image */

/* Clean up after the read, and free any memory allocated-required */
Png_destroy_read_struct (& png_ptr, & info_ptr, png_infopp_null );

/* Close the file */
Fclose (FP );

/* That's it */
Return (OK );
}

/* Progressively read a file */

 

For interplace files, it is critical to use PNG updateinfo for smooth reading.

Writing files is similar. You can refer to the related functions in example.

In addition, pnglib is used to read and write files. The best demo is cximage. You can find it.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.