IMG_png.c
author Sam Lantinga <slouken@libsdl.org>
Sat, 04 Feb 2006 20:37:17 +0000
changeset 117 e613cf987897
parent 100 3feaaa4104f6
child 118 c5e736a47ad2
permissions -rw-r--r--
Fixed image type functions so they seek back to where they started
     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 	int start;
    80 	int is_PNG;
    81 	unsigned char buf[PNG_BYTES_TO_CHECK];
    82 
    83 	start = SDL_RWtell(src);
    84 	is_PNG = 0;
    85 	if ( SDL_RWread(src, buf, 1, PNG_BYTES_TO_CHECK) == PNG_BYTES_TO_CHECK ) {
    86 		is_PNG = (png_sig_cmp(buf, (png_size_t)0, PNG_BYTES_TO_CHECK) == 0);
    87 	}
    88 	SDL_RWseek(src, start, SEEK_SET);
    89 	return(is_PNG);
    90 }
    91 
    92 /* Load a PNG type image from an SDL datasource */
    93 static void png_read_data(png_structp ctx, png_bytep area, png_size_t size)
    94 {
    95 	SDL_RWops *src;
    96 
    97 	src = (SDL_RWops *)png_get_io_ptr(ctx);
    98 	SDL_RWread(src, area, size, 1);
    99 }
   100 SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src)
   101 {
   102 	SDL_Surface *volatile surface;
   103 	png_structp png_ptr;
   104 	png_infop info_ptr;
   105 	png_uint_32 width, height;
   106 	int bit_depth, color_type, interlace_type;
   107 	Uint32 Rmask;
   108 	Uint32 Gmask;
   109 	Uint32 Bmask;
   110 	Uint32 Amask;
   111 	SDL_Palette *palette;
   112 	png_bytep *volatile row_pointers;
   113 	int row, i;
   114 	volatile int ckey = -1;
   115 	png_color_16 *transv;
   116 
   117 	if ( !src ) {
   118 		/* The error message has been set in SDL_RWFromFile */
   119 		return NULL;
   120 	}
   121 
   122 	/* Initialize the data we will clean up when we're done */
   123 	png_ptr = NULL; info_ptr = NULL; row_pointers = NULL; surface = NULL;
   124 
   125 	/* Create the PNG loading context structure */
   126 	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
   127 					  NULL,NULL,NULL);
   128 	if (png_ptr == NULL){
   129 		IMG_SetError("Couldn't allocate memory for PNG file or incompatible PNG dll");
   130 		goto done;
   131 	}
   132 
   133 	 /* Allocate/initialize the memory for image information.  REQUIRED. */
   134 	info_ptr = png_create_info_struct(png_ptr);
   135 	if (info_ptr == NULL) {
   136 		IMG_SetError("Couldn't create image information for PNG file");
   137 		goto done;
   138 	}
   139 
   140 	/* Set error handling if you are using setjmp/longjmp method (this is
   141 	 * the normal method of doing things with libpng).  REQUIRED unless you
   142 	 * set up your own error handlers in png_create_read_struct() earlier.
   143 	 */
   144 	if ( setjmp(png_ptr->jmpbuf) ) {
   145 		IMG_SetError("Error reading the PNG file.");
   146 		goto done;
   147 	}
   148 
   149 	/* Set up the input control */
   150 	png_set_read_fn(png_ptr, src, png_read_data);
   151 
   152 	/* Read PNG header info */
   153 	png_read_info(png_ptr, info_ptr);
   154 	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
   155 			&color_type, &interlace_type, NULL, NULL);
   156 
   157 	/* tell libpng to strip 16 bit/color files down to 8 bits/color */
   158 	png_set_strip_16(png_ptr) ;
   159 
   160 	/* Extract multiple pixels with bit depths of 1, 2, and 4 from a single
   161 	 * byte into separate bytes (useful for paletted and grayscale images).
   162 	 */
   163 	png_set_packing(png_ptr);
   164 
   165 	/* scale greyscale values to the range 0..255 */
   166 	if(color_type == PNG_COLOR_TYPE_GRAY)
   167 		png_set_expand(png_ptr);
   168 
   169 	/* For images with a single "transparent colour", set colour key;
   170 	   if more than one index has transparency, or if partially transparent
   171 	   entries exist, use full alpha channel */
   172 	if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
   173 	        int num_trans;
   174 		Uint8 *trans;
   175 		png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans,
   176 			     &transv);
   177 		if(color_type == PNG_COLOR_TYPE_PALETTE) {
   178 		    /* Check if all tRNS entries are opaque except one */
   179 		    int i, t = -1;
   180 		    for(i = 0; i < num_trans; i++)
   181 			if(trans[i] == 0) {
   182 			    if(t >= 0)
   183 				break;
   184 			    t = i;
   185 			} else if(trans[i] != 255)
   186 			    break;
   187 		    if(i == num_trans) {
   188 			/* exactly one transparent index */
   189 			ckey = t;
   190 		    } else {
   191 			/* more than one transparent index, or translucency */
   192 			png_set_expand(png_ptr);
   193 		    }
   194 		} else
   195 		    ckey = 0; /* actual value will be set later */
   196 	}
   197 
   198 	if ( color_type == PNG_COLOR_TYPE_GRAY_ALPHA )
   199 		png_set_gray_to_rgb(png_ptr);
   200 
   201 	png_read_update_info(png_ptr, info_ptr);
   202 
   203 	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
   204 			&color_type, &interlace_type, NULL, NULL);
   205 
   206 	/* Allocate the SDL surface to hold the image */
   207 	Rmask = Gmask = Bmask = Amask = 0 ; 
   208 	if ( color_type != PNG_COLOR_TYPE_PALETTE ) {
   209 		if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) {
   210 			Rmask = 0x000000FF;
   211 			Gmask = 0x0000FF00;
   212 			Bmask = 0x00FF0000;
   213 			Amask = (info_ptr->channels == 4) ? 0xFF000000 : 0;
   214 		} else {
   215 		        int s = (info_ptr->channels == 4) ? 0 : 8;
   216 			Rmask = 0xFF000000 >> s;
   217 			Gmask = 0x00FF0000 >> s;
   218 			Bmask = 0x0000FF00 >> s;
   219 			Amask = 0x000000FF >> s;
   220 		}
   221 	}
   222 	surface = SDL_AllocSurface(SDL_SWSURFACE, width, height,
   223 			bit_depth*info_ptr->channels, Rmask,Gmask,Bmask,Amask);
   224 	if ( surface == NULL ) {
   225 		IMG_SetError("Out of memory");
   226 		goto done;
   227 	}
   228 
   229 	if(ckey != -1) {
   230 	        if(color_type != PNG_COLOR_TYPE_PALETTE)
   231 			/* FIXME: Should these be truncated or shifted down? */
   232 		        ckey = SDL_MapRGB(surface->format,
   233 			                 (Uint8)transv->red,
   234 			                 (Uint8)transv->green,
   235 			                 (Uint8)transv->blue);
   236 	        SDL_SetColorKey(surface, SDL_SRCCOLORKEY, ckey);
   237 	}
   238 
   239 	/* Create the array of pointers to image data */
   240 	row_pointers = (png_bytep*) malloc(sizeof(png_bytep)*height);
   241 	if ( (row_pointers == NULL) ) {
   242 		IMG_SetError("Out of memory");
   243 		SDL_FreeSurface(surface);
   244 		surface = NULL;
   245 		goto done;
   246 	}
   247 	for (row = 0; row < (int)height; row++) {
   248 		row_pointers[row] = (png_bytep)
   249 				(Uint8 *)surface->pixels + row*surface->pitch;
   250 	}
   251 
   252 	/* Read the entire image in one go */
   253 	png_read_image(png_ptr, row_pointers);
   254 
   255 	/* and we're done!  (png_read_end() can be omitted if no processing of
   256 	 * post-IDAT text/time/etc. is desired)
   257 	 * In some cases it can't read PNG's created by some popular programs (ACDSEE),
   258 	 * we do not want to process comments, so we omit png_read_end
   259 
   260 	png_read_end(png_ptr, info_ptr);
   261 	*/
   262 
   263 	/* Load the palette, if any */
   264 	palette = surface->format->palette;
   265 	if ( palette ) {
   266 	    if(color_type == PNG_COLOR_TYPE_GRAY) {
   267 		palette->ncolors = 256;
   268 		for(i = 0; i < 256; i++) {
   269 		    palette->colors[i].r = i;
   270 		    palette->colors[i].g = i;
   271 		    palette->colors[i].b = i;
   272 		}
   273 	    } else if (info_ptr->num_palette > 0 ) {
   274 		palette->ncolors = info_ptr->num_palette; 
   275 		for( i=0; i<info_ptr->num_palette; ++i ) {
   276 		    palette->colors[i].b = info_ptr->palette[i].blue;
   277 		    palette->colors[i].g = info_ptr->palette[i].green;
   278 		    palette->colors[i].r = info_ptr->palette[i].red;
   279 		}
   280 	    }
   281 	}
   282 
   283 done:	/* Clean up and return */
   284 	png_destroy_read_struct(&png_ptr, info_ptr ? &info_ptr : (png_infopp)0,
   285 								(png_infopp)0);
   286 	if ( row_pointers ) {
   287 		free(row_pointers);
   288 	}
   289 	return(surface); 
   290 }
   291 
   292 #else
   293 
   294 /* See if an image is contained in a data source */
   295 int IMG_isPNG(SDL_RWops *src)
   296 {
   297 	return(0);
   298 }
   299 
   300 /* Load a PNG type image from an SDL datasource */
   301 SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src)
   302 {
   303 	return(NULL);
   304 }
   305 
   306 #endif /* LOAD_PNG */