IMG_png.c
author Sam Lantinga <slouken@libsdl.org>
Sun, 04 Jan 2004 17:41:55 +0000
changeset 97 e1161bd417c4
parent 95 7fcb46931afc
child 98 9f94c4674cc9
permissions -rw-r--r--
Updated copyright information for 2004 (Happy New Year!)
     1 /*
     2     SDL_image:  An example image loading library for use with SDL
     3     Copyright (C) 1999-2004 Sam Lantinga
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Library General Public
     7     License as published by the Free Software Foundation; either
     8     version 2 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Library General Public License for more details.
    14 
    15     You should have received a copy of the GNU Library General Public
    16     License along with this library; if not, write to the Free
    17     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    18 
    19     Sam Lantinga
    20     slouken@libsdl.org
    21 */
    22 
    23 /* $Id$ */
    24 
    25 /* This is a PNG image file loading framework */
    26 
    27 #include <stdlib.h>
    28 #include <stdio.h>
    29 
    30 #include "SDL_image.h"
    31 
    32 #ifdef LOAD_PNG
    33 
    34 /*=============================================================================
    35         File: SDL_png.c
    36      Purpose: A PNG loader and saver for the SDL library      
    37     Revision: 
    38   Created by: Philippe Lavoie          (2 November 1998)
    39               lavoie@zeus.genie.uottawa.ca
    40  Modified by: 
    41 
    42  Copyright notice:
    43           Copyright (C) 1998 Philippe Lavoie
    44  
    45           This library is free software; you can redistribute it and/or
    46           modify it under the terms of the GNU Library General Public
    47           License as published by the Free Software Foundation; either
    48           version 2 of the License, or (at your option) any later version.
    49  
    50           This library is distributed in the hope that it will be useful,
    51           but WITHOUT ANY WARRANTY; without even the implied warranty of
    52           MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    53           Library General Public License for more details.
    54  
    55           You should have received a copy of the GNU Library General Public
    56           License along with this library; if not, write to the Free
    57           Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
    58 
    59     Comments: The load and save routine are basically the ones you can find
    60              in the example.c file from the libpng distribution.
    61 
    62   Changes:
    63     5/17/99 - Modified to use the new SDL data sources - Sam Lantinga
    64 
    65 =============================================================================*/
    66 
    67 #include "SDL_endian.h"
    68 
    69 #ifdef macintosh
    70 #define MACOS
    71 #endif
    72 #include <png.h>
    73 
    74 #define PNG_BYTES_TO_CHECK 4
    75 
    76 /* See if an image is contained in a data source */
    77 int IMG_isPNG(SDL_RWops *src)
    78 {
    79    unsigned char buf[PNG_BYTES_TO_CHECK];
    80 
    81    /* Read in the signature bytes */
    82    if (SDL_RWread(src, buf, 1, PNG_BYTES_TO_CHECK) != PNG_BYTES_TO_CHECK)
    83       return 0;
    84 
    85    /* Compare the first PNG_BYTES_TO_CHECK bytes of the signature. */
    86    return( !png_sig_cmp(buf, (png_size_t)0, PNG_BYTES_TO_CHECK));
    87 }
    88 
    89 /* Load a PNG type image from an SDL datasource */
    90 static void png_read_data(png_structp ctx, png_bytep area, png_size_t size)
    91 {
    92 	SDL_RWops *src;
    93 
    94 	src = (SDL_RWops *)png_get_io_ptr(ctx);
    95 	SDL_RWread(src, area, size, 1);
    96 }
    97 SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src)
    98 {
    99 	SDL_Surface *volatile surface;
   100 	png_structp png_ptr;
   101 	png_infop info_ptr;
   102 	png_uint_32 width, height;
   103 	int bit_depth, color_type, interlace_type;
   104 	Uint32 Rmask;
   105 	Uint32 Gmask;
   106 	Uint32 Bmask;
   107 	Uint32 Amask;
   108 	SDL_Palette *palette;
   109 	png_bytep *volatile row_pointers;
   110 	int row, i;
   111 	volatile int ckey = -1;
   112 	png_color_16 *transv;
   113 
   114 	/* Initialize the data we will clean up when we're done */
   115 	png_ptr = NULL; info_ptr = NULL; row_pointers = NULL; surface = NULL;
   116 
   117 	/* Create the PNG loading context structure */
   118 	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
   119 					  NULL,NULL,NULL);
   120 	if (png_ptr == NULL){
   121 		IMG_SetError("Couldn't allocate memory for PNG file");
   122 		goto done;
   123 	}
   124 
   125 	 /* Allocate/initialize the memory for image information.  REQUIRED. */
   126 	info_ptr = png_create_info_struct(png_ptr);
   127 	if (info_ptr == NULL) {
   128 		IMG_SetError("Couldn't create image information for PNG file");
   129 		goto done;
   130 	}
   131 
   132 	/* Set error handling if you are using setjmp/longjmp method (this is
   133 	 * the normal method of doing things with libpng).  REQUIRED unless you
   134 	 * set up your own error handlers in png_create_read_struct() earlier.
   135 	 */
   136 	if ( setjmp(png_ptr->jmpbuf) ) {
   137 		IMG_SetError("Error reading the PNG file.");
   138 		goto done;
   139 	}
   140 
   141 	/* Set up the input control */
   142 	png_set_read_fn(png_ptr, src, png_read_data);
   143 
   144 	/* Read PNG header info */
   145 	png_read_info(png_ptr, info_ptr);
   146 	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
   147 			&color_type, &interlace_type, NULL, NULL);
   148 
   149 	/* tell libpng to strip 16 bit/color files down to 8 bits/color */
   150 	png_set_strip_16(png_ptr) ;
   151 
   152 	/* Extract multiple pixels with bit depths of 1, 2, and 4 from a single
   153 	 * byte into separate bytes (useful for paletted and grayscale images).
   154 	 */
   155 	png_set_packing(png_ptr);
   156 
   157 	/* scale greyscale values to the range 0..255 */
   158 	if(color_type == PNG_COLOR_TYPE_GRAY)
   159 		png_set_expand(png_ptr);
   160 
   161 	/* For images with a single "transparent colour", set colour key;
   162 	   if more than one index has transparency, or if partially transparent
   163 	   entries exist, use full alpha channel */
   164 	if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
   165 	        int num_trans;
   166 		Uint8 *trans;
   167 		png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans,
   168 			     &transv);
   169 		if(color_type == PNG_COLOR_TYPE_PALETTE) {
   170 		    /* Check if all tRNS entries are opaque except one */
   171 		    int i, t = -1;
   172 		    for(i = 0; i < num_trans; i++)
   173 			if(trans[i] == 0) {
   174 			    if(t >= 0)
   175 				break;
   176 			    t = i;
   177 			} else if(trans[i] != 255)
   178 			    break;
   179 		    if(i == num_trans) {
   180 			/* exactly one transparent index */
   181 			ckey = t;
   182 		    } else {
   183 			/* more than one transparent index, or translucency */
   184 			png_set_expand(png_ptr);
   185 		    }
   186 		} else
   187 		    ckey = 0; /* actual value will be set later */
   188 	}
   189 
   190 	if ( color_type == PNG_COLOR_TYPE_GRAY_ALPHA )
   191 		png_set_gray_to_rgb(png_ptr);
   192 
   193 	png_read_update_info(png_ptr, info_ptr);
   194 
   195 	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
   196 			&color_type, &interlace_type, NULL, NULL);
   197 
   198 	/* Allocate the SDL surface to hold the image */
   199 	Rmask = Gmask = Bmask = Amask = 0 ; 
   200 	if ( color_type != PNG_COLOR_TYPE_PALETTE ) {
   201 		if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) {
   202 			Rmask = 0x000000FF;
   203 			Gmask = 0x0000FF00;
   204 			Bmask = 0x00FF0000;
   205 			Amask = (info_ptr->channels == 4) ? 0xFF000000 : 0;
   206 		} else {
   207 		        int s = (info_ptr->channels == 4) ? 0 : 8;
   208 			Rmask = 0xFF000000 >> s;
   209 			Gmask = 0x00FF0000 >> s;
   210 			Bmask = 0x0000FF00 >> s;
   211 			Amask = 0x000000FF >> s;
   212 		}
   213 	}
   214 	surface = SDL_AllocSurface(SDL_SWSURFACE, width, height,
   215 			bit_depth*info_ptr->channels, Rmask,Gmask,Bmask,Amask);
   216 	if ( surface == NULL ) {
   217 		IMG_SetError("Out of memory");
   218 		goto done;
   219 	}
   220 
   221 	if(ckey != -1) {
   222 	        if(color_type != PNG_COLOR_TYPE_PALETTE)
   223 			/* FIXME: Should these be truncated or shifted down? */
   224 		        ckey = SDL_MapRGB(surface->format,
   225 			                 (Uint8)transv->red,
   226 			                 (Uint8)transv->green,
   227 			                 (Uint8)transv->blue);
   228 	        SDL_SetColorKey(surface, SDL_SRCCOLORKEY, ckey);
   229 	}
   230 
   231 	/* Create the array of pointers to image data */
   232 	row_pointers = (png_bytep*) malloc(sizeof(png_bytep)*height);
   233 	if ( (row_pointers == NULL) ) {
   234 		IMG_SetError("Out of memory");
   235 		SDL_FreeSurface(surface);
   236 		surface = NULL;
   237 		goto done;
   238 	}
   239 	for (row = 0; row < (int)height; row++) {
   240 		row_pointers[row] = (png_bytep)
   241 				(Uint8 *)surface->pixels + row*surface->pitch;
   242 	}
   243 
   244 	/* Read the entire image in one go */
   245 	png_read_image(png_ptr, row_pointers);
   246 
   247 	/* read rest of file, get additional chunks in info_ptr - REQUIRED */
   248 	png_read_end(png_ptr, info_ptr);
   249 
   250 	/* Load the palette, if any */
   251 	palette = surface->format->palette;
   252 	if ( palette ) {
   253 	    if(color_type == PNG_COLOR_TYPE_GRAY) {
   254 		palette->ncolors = 256;
   255 		for(i = 0; i < 256; i++) {
   256 		    palette->colors[i].r = i;
   257 		    palette->colors[i].g = i;
   258 		    palette->colors[i].b = i;
   259 		}
   260 	    } else if (info_ptr->num_palette > 0 ) {
   261 		palette->ncolors = info_ptr->num_palette; 
   262 		for( i=0; i<info_ptr->num_palette; ++i ) {
   263 		    palette->colors[i].b = info_ptr->palette[i].blue;
   264 		    palette->colors[i].g = info_ptr->palette[i].green;
   265 		    palette->colors[i].r = info_ptr->palette[i].red;
   266 		}
   267 	    }
   268 	}
   269 
   270 done:	/* Clean up and return */
   271 	png_destroy_read_struct(&png_ptr, info_ptr ? &info_ptr : (png_infopp)0,
   272 								(png_infopp)0);
   273 	if ( row_pointers ) {
   274 		free(row_pointers);
   275 	}
   276 	return(surface); 
   277 }
   278 
   279 #else
   280 
   281 /* See if an image is contained in a data source */
   282 int IMG_isPNG(SDL_RWops *src)
   283 {
   284 	return(0);
   285 }
   286 
   287 /* Load a PNG type image from an SDL datasource */
   288 SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src)
   289 {
   290 	return(NULL);
   291 }
   292 
   293 #endif /* LOAD_PNG */