Png image decoding and png Decoding

Source: Internet
Author: User
Tags call back file info

Png image decoding and png Decoding

PNG, a Portable Network image Format (PNG), is derived from the unofficial "PNG's Not GIF" and is a bitmap file storage Format. 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.

The PNG format can be 8-bit, 24-bit, and 32-bit. The 8-bit PNG format supports two different transparent formats (index transparency and alpha transparency), and the 24-bit PNG format does not support transparency, 32-bit PNG adds an 8-bit transparent channel based on 24-bit, so it can display 256 levels of transparency.
The numbers after PNG8 and PNG24 represent the maximum color values that can be indexed and stored in this PNG format ." 8 "represents the power of 2, that is, 256 colors, and 24 represents that the power of 2 is about more than 16 million colors.

Format Supports up to Color Channels Index color editing support Transparent support
PNG8 256 index color Supported Allows you to set a specific index color to transparent (Boolean transparent)
Supports attaching 8-bit transparency to the index color (level 256 alpha transparency)
PNG24 About 16 million colors Not Supported Not Supported
PNG32 About 16 million colors Not Supported Supports 8-bit transparency (level 1 alpha transparency)

The PNG file format retains the following features of the GIF file format:

  • You can use a color search table or a color palette to support color images of 256 colors;
  • Streamability: The image file format allows continuous reading and writing of image data. This feature is suitable for generating and displaying images during communication;
  • Progressive display: This feature enables you to display images on the terminal while transmitting image files on the communication link. After the entire outline is displayed, the image details are gradually displayed, that is, first display the image with low resolution, and then gradually improve its resolution;
  • Transparency: This performance prevents certain parts of the image from being displayed and is used to create distinctive images.
  • Ancillary information: this feature can be used to store text comments in image files;
  • Independent from computer software and hardware environments;
  • Use lossless compression.

Add the following features not available in the GIF file format:

  • Each pixel is a 48-bit real-color image;
  • Each pixel is a 16-bit grayscale image;
  • You can add Alpha channels for Grayscale and true color graphs;
  • Add the Gamma information of the image;
  • Use cyclic redundancy code (CRC) to detect damaged files;
  • Accelerate the Display Method of Image Display by successive approximation;
  • Standard read/write toolkit;
  • Multiple images can be stored in one file.

File structure

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.

Decimal number 137 80 78 71 13 10 26 10
Hexadecimal number 89 50 4e 47 0d 0a 1a 0a

The first byte 0x89 is out of the ASCII character range to prevent some software from processing PNG files as text files. The remaining parts of the file are composed of more than three PNG data blocks (Chunk) in a specific order. Therefore, a standard PNG file structure should be as follows:

PNG file flag PNG data block ... PNG data block

So we can see the judgment function in png format in-x:

bool Image::isPng(const unsigned char * data, ssize_t dataLen){    if (dataLen <= 8)    {        return false;    }    static const unsigned char PNG_SIGNATURE[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};    return memcmp(PNG_SIGNATURE, data, sizeof(PNG_SIGNATURE)) == 0;}
Data blocks in PNG file format
Data Block symbol Data Block name Multiple Data blocks Optional Location restrictions
IHDR File header data block No No First
CHRM Base color and white point data block No Yes Before PLTE and IDAT
GAMA Image gamma data block No Yes Before PLTE and IDAT
SBIT Sample valid BIT data block No Yes Before PLTE and IDAT
PLTE Color Palette data block No Yes Before IDAT
BKGD Background color data block No Yes Before IDAT after PLTE
HIST Image histogram data block No Yes Before IDAT after PLTE
TRNS Transparent data block No Yes Before IDAT after PLTE
OFFs (Private Public Data blocks) No Yes Before IDAT
PHYs Physical pixel size data block No Yes Before IDAT
SCAL (Private Public Data blocks) No Yes Before IDAT
IDAT Image Data Block Yes No Continuous with other IDAT
TIME Last modification time data block of the image No Yes Unlimited
TEXt Text Information Data Block Yes Yes Unlimited
ZTXt Compressing text data blocks Yes Yes Unlimited
FRAc (Private Public Data blocks) Yes Yes Unlimited
GIFg (Private Public Data blocks) Yes Yes Unlimited
GIFt (Private Public Data blocks) Yes Yes Unlimited
GIFx (Private Public Data blocks) Yes Yes Unlimited
IEND Image end data No No Last data block

Data Block Structure

Name Bytes Description
Length) 4 bytes Specifies the length of the data field in a data block. The length cannot exceed (231-1) bytes.
Chunk Type Code (data block Type Code) 4 bytes The data block type code consists of ASCII letters (A-Z and a-z)
Chunk Data (Data block Data) Variable Length Store data specified by Chunk Type Code
CRC (Cyclic Redundancy detection) 4 bytes The storage is used to check whether there are error cyclic verification codes.

IHDR

Header chunk: it contains the basic information of the image data stored in the PNG file and needs to appear as the first data block in the PNG data stream, in addition, a PNG data stream can only contain one file header data block. The file header data block consists of 13 bytes. Its format is shown in the following table.

Domain Name Bytes Description
Length) 4 bytes Image Width, in pixels
Height 4 bytes Image Height, in pixels
Bit depth 1 byte Image depth:
Indexed color images: 1, 2, 4, or 8
Grayscale Images: 1, 2, 4, 8, or 16
True Color Image: 8 or 16
ColorType 1 byte Color type:
0: grayscale image, 1, 2, 4, 8, or 16
2: true color image, 8 or 16
3: indexing color images, 1, 2, 4, or 8
4: grayscale image with alpha channel data, 8 or 16
6: true color image with alpha channel data, 8 or 16
Compression method 1 byte Compression Method (LZ77 derived algorithm)
Filter method 1 byte Filter Method
Interencryption method 1 byte How to scan through multiple rows:
0: Non-interlace Scan
1: Adam7 (7 times of interlace scan developed by Adam M. Costello)

PLTE

The palette data block PLTE (palette chunk) contains color transformation data related to indexed-color image, which is only related to indexed color images, it must be placed before the image data chunk.

PLTE data blocks are the palette information that defines the image. PLTE can contain 1 ~ There are 256 color palette information. Each color palette information consists of three bytes of RGB. Therefore, the color palette length should be a multiple of three. Otherwise, this would be an invalid color palette. Similarly, the maximum number of bytes contained in the palette data block is 768.

For indexed images, the color palette information is required. The color index of the palette starts from 0, followed by 1, 2 ......, The number of colors in the color palette cannot exceed the number of colors specified in the color depth (when the color depth is 4, the number of colors in the color palette cannot exceed 2 ^ 4 = 16). Otherwise, this will cause the PNG image to be invalid.

Real-color images and true-color images with alpha channel data can also have color palette data blocks, so that the non-real-color display program can use it to quantify image data and display the image.

IDAT

Image data Block IDAT (image data chunk): It stores actual data and can contain multiple consecutive sequential image data blocks in the data stream.

IDAT stores the real data information of the image. Therefore, if we can understand the IDAT structure, we can easily generate PNG images.

IEND

Image trailer chunk: it indicates that a PNG file or data stream has ended and must be placed at the end of the file. If we carefully observe the PNG file, we will find that the last 12 characters of the file should always look like this:

00 00 00 00 49 45 4E 44 AE 42 60 82

It is hard to understand that due to the definition of the data block structure, the length of the IEND data block is always 0 (00 00 00 00, unless information is manually added), and the data mark is always IEND (49 45 4E 44 ), therefore, the CRC code is always AE 42 60 82.

Cocos2dx libpng Decoding

Bool Image: initWithPngData (const unsigned char * data, ssize_t dataLen) {// length of bytes to check if it is a valid png file # define PNGSIGSIZE 8 bool ret = false; png_byte header [PNGSIGSIZE] = {0}; png_structp png_ptr = 0; png_infop info_ptr = 0; do {// png header len is 8 bytes CC_BREAK_IF (dataLen <PNGSIGSIZE ); // file header check // check the data is png or not memcpy (header, data, PNGSIGSIZE); CC_BREAK _ IF (png_sig_cmp (header, 0, PNGSIGSIZE); // initialize the png_structp type struct, and use the // init png_struct png_ptr = png_create_read_struct (bytes, 0, 0, 0) in libpng ); CC_BREAK_IF (! Png_ptr); // Create Image Information // init png_info info_ptr = png_create_info_struct (png_ptr); CC_BREAK_IF (! Info_ptr); # if (CC_TARGET_PLATFORM! = CC_PLATFORM_BADA & CC_TARGET_PLATFORM! = CC_PLATFORM_NACL) // sets CC_BREAK_IF (setjmp (png_jmpbuf (png_ptr) for exception handling ))); # endif // use the custom callback function to set the libpng data source // set the read call back function tImageSource imageSource; imageSource. data = (unsigned char *) data; imageSource. size = dataLen; imageSource. offset = 0; png_set_read_fn (png_ptr, & imageSource, pngReadCallback); // read png header info // use underlying processing to read png data // read png file info png_read_info (png_ptr, I Nfo_ptr); // query Image Information _ width = rows (png_ptr, info_ptr); _ height = png_get_image_height (png_ptr, info_ptr); png_byte bit_depth = rows (png_ptr, info_ptr ); png_uint_32 color_type = png_get_color_type (png_ptr, info_ptr); // CCLOG ("color type % u", color_type); // png Image in the color palette format, convert to RGB888 pixel format // force palette images to be expanded to 24-bit RGB // it may include alpha channel if (co Lor_type = PNG_COLOR_TYPE_PALETTE) {png_set_palette_to_rgb (png_ptr);} // grayscale map with a pixel format less than 1 byte, convert it to the pixel format of 1 byte per pixel // low-bit-depth grayscale images are to be expanded to 8 bits if (color_type = PNG_COLOR_TYPE_GRAY & bit_depth <8) {bit_depth = 8; png_set_expand_gray_1_2_4_to_8 (png_ptr );} // extend the tRNS block data information to the complete ALPHA channel information // expand any tRNS chunk data into a full alpha channel if (png_get_valid (png_ptr, in Fo_ptr, PNG_INFO_tRNS) {png_set_tRNS_to_alpha (png_ptr);} // reduce 16-bit input to 8-bit/reduce images with 16-bit samples to 8 bits if (bit_depth = 16) {png_set_strip_16 (png_ptr);} // Expanded earlier for grayscale, now take care of palette and rgb if (bit_depth <8) {png_set_packing (png_ptr );} // update png data details // update info png_read_update_info (png_ptr, info_ptr); bit_depth = png_get_bit_depth (png_ptr, I Nfo_ptr); color_type = cursor (png_ptr, info_ptr); switch (color_type) {case PNG_COLOR_TYPE_GRAY: _ renderFormat = Texture2D: PixelFormat: I8; break; case when: _ renderFormat = Texture2D: PixelFormat: AI88; break; case when: _ renderFormat = Texture2D: PixelFormat: RGB888; break; case when: _ renderFormat = Texture2D: PixelFormat:: RGB A8888; break; default: break;} // read png information by row, // read png data into rowbytes; png_bytep * row_pointers = (png_bytep *) malloc (sizeof (png_bytep) * _ height); // get the number of bytes in each row of pixels rowbytes = png_get_rowbytes (png_ptr, info_ptr); // apply for the memory address _ dataLen = rowbytes * _ height; _ data = static_cast <unsigned char *> (malloc (_ dataLen * sizeof (unsigned char); if (! _ Data) {if (row_pointers! = Nullptr) {free (row_pointers);} break;} for (unsigned short I = 0; I <_ height; ++ I) {row_pointers [I] = _ data + I * rowbytes;} // read png data png_read_image (png_ptr, row_pointers); // end png_read_end (png_ptr, nullptr ); // premultiplied alpha for RGBA8888 if (color_type = strong) {// pre-multiply Alpha, use gradient Alpha premultipliedAlpha ();} else {_ hasPremultipliedAlpha = false;} if (row_point Ers! = Nullptr) {// release the image data memory free (row_pointers);} ret = true;} while (0); if (png_ptr) {// release png_ptr png_destroy_read_struct (& png_ptr, (info_ptr )? & Info_ptr: 0, 0);} return ret ;}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

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.