IMG_png.c
author Sam Lantinga <slouken@libsdl.org>
Fri, 14 Dec 2001 13:02:16 +0000
changeset 53 96b084473b47
parent 41 0cda6740c745
child 95 7fcb46931afc
permissions -rw-r--r--
*** empty log message ***
     1 /*
     2     SDL_image:  An example image loading library for use with SDL
     3     Copyright (C) 1999, 2000, 2001  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 	/* Check to make sure we have something to do */
   118 	if ( ! src ) {
   119 		goto done;
   120 	}
   121 
   122 	/* Create the PNG loading context structure */
   123 	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
   124 					  NULL,NULL,NULL);
   125 	if (png_ptr == NULL){
   126 		IMG_SetError("Couldn't allocate memory for PNG file");
   127 		goto done;
   128 	}
   129 
   130 	 /* Allocate/initialize the memory for image information.  REQUIRED. */
   131 	info_ptr = png_create_info_struct(png_ptr);
   132 	if (info_ptr == NULL) {
   133 		IMG_SetError("Couldn't create image information for PNG file");
   134 		goto done;
   135 	}
   136 
   137 	/* Set error handling if you are using setjmp/longjmp method (this is
   138 	 * the normal method of doing things with libpng).  REQUIRED unless you
   139 	 * set up your own error handlers in png_create_read_struct() earlier.
   140 	 */
   141 	if ( setjmp(png_ptr->jmpbuf) ) {
   142 		IMG_SetError("Error reading the PNG file.");
   143 		goto done;
   144 	}
   145 
   146 	/* Set up the input control */
   147 	png_set_read_fn(png_ptr, src, png_read_data);
   148 
   149 	/* Read PNG header info */
   150 	png_read_info(png_ptr, info_ptr);
   151 	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
   152 			&color_type, &interlace_type, NULL, NULL);
   153 
   154 	/* tell libpng to strip 16 bit/color files down to 8 bits/color */
   155 	png_set_strip_16(png_ptr) ;
   156 
   157 	/* Extract multiple pixels with bit depths of 1, 2, and 4 from a single
   158 	 * byte into separate bytes (useful for paletted and grayscale images).
   159 	 */
   160 	png_set_packing(png_ptr);
   161 
   162 	/* scale greyscale values to the range 0..255 */
   163 	if(color_type == PNG_COLOR_TYPE_GRAY)
   164 		png_set_expand(png_ptr);
   165 
   166 	/* For images with a single "transparent colour", set colour key;
   167 	   if more than one index has transparency, or if partially transparent
   168 	   entries exist, use full alpha channel */
   169 	if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
   170 	        int num_trans;
   171 		Uint8 *trans;
   172 		png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans,
   173 			     &transv);
   174 		if(color_type == PNG_COLOR_TYPE_PALETTE) {
   175 		    /* Check if all tRNS entries are opaque except one */
   176 		    int i, t = -1;
   177 		    for(i = 0; i < num_trans; i++)
   178 			if(trans[i] == 0) {
   179 			    if(t >= 0)
   180 				break;
   181 			    t = i;
   182 			} else if(trans[i] != 255)
   183 			    break;
   184 		    if(i == num_trans) {
   185 			/* exactly one transparent index */
   186 			ckey = t;
   187 		    } else {
   188 			/* more than one transparent index, or translucency */
   189 			png_set_expand(png_ptr);
   190 		    }
   191 		} else
   192 		    ckey = 0; /* actual value will be set later */
   193 	}
   194 
   195 	if ( color_type == PNG_COLOR_TYPE_GRAY_ALPHA )
   196 		png_set_gray_to_rgb(png_ptr);
   197 
   198 	png_read_update_info(png_ptr, info_ptr);
   199 
   200 	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
   201 			&color_type, &interlace_type, NULL, NULL);
   202 
   203 	/* Allocate the SDL surface to hold the image */
   204 	Rmask = Gmask = Bmask = Amask = 0 ; 
   205 	if ( color_type != PNG_COLOR_TYPE_PALETTE ) {
   206 		if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) {
   207 			Rmask = 0x000000FF;
   208 			Gmask = 0x0000FF00;
   209 			Bmask = 0x00FF0000;
   210 			Amask = (info_ptr->channels == 4) ? 0xFF000000 : 0;
   211 		} else {
   212 		        int s = (info_ptr->channels == 4) ? 0 : 8;
   213 			Rmask = 0xFF000000 >> s;
   214 			Gmask = 0x00FF0000 >> s;
   215 			Bmask = 0x0000FF00 >> s;
   216 			Amask = 0x000000FF >> s;
   217 		}
   218 	}
   219 	surface = SDL_AllocSurface(SDL_SWSURFACE, width, height,
   220 			bit_depth*info_ptr->channels, Rmask,Gmask,Bmask,Amask);
   221 	if ( surface == NULL ) {
   222 		IMG_SetError("Out of memory");
   223 		goto done;
   224 	}
   225 
   226 	if(ckey != -1) {
   227 	        if(color_type != PNG_COLOR_TYPE_PALETTE)
   228 			/* FIXME: Should these be truncated or shifted down? */
   229 		        ckey = SDL_MapRGB(surface->format,
   230 			                 (Uint8)transv->red,
   231 			                 (Uint8)transv->green,
   232 			                 (Uint8)transv->blue);
   233 	        SDL_SetColorKey(surface, SDL_SRCCOLORKEY, ckey);
   234 	}
   235 
   236 	/* Create the array of pointers to image data */
   237 	row_pointers = (png_bytep*) malloc(sizeof(png_bytep)*height);
   238 	if ( (row_pointers == NULL) ) {
   239 		IMG_SetError("Out of memory");
   240 		SDL_FreeSurface(surface);
   241 		surface = NULL;
   242 		goto done;
   243 	}
   244 	for (row = 0; row < (int)height; row++) {
   245 		row_pointers[row] = (png_bytep)
   246 				(Uint8 *)surface->pixels + row*surface->pitch;
   247 	}
   248 
   249 	/* Read the entire image in one go */
   250 	png_read_image(png_ptr, row_pointers);
   251 
   252 	/* read rest of file, get additional chunks in info_ptr - REQUIRED */
   253 	png_read_end(png_ptr, info_ptr);
   254 
   255 	/* Load the palette, if any */
   256 	palette = surface->format->palette;
   257 	if ( palette ) {
   258 	    if(color_type == PNG_COLOR_TYPE_GRAY) {
   259 		palette->ncolors = 256;
   260 		for(i = 0; i < 256; i++) {
   261 		    palette->colors[i].r = i;
   262 		    palette->colors[i].g = i;
   263 		    palette->colors[i].b = i;
   264 		}
   265 	    } else if (info_ptr->num_palette > 0 ) {
   266 		palette->ncolors = info_ptr->num_palette; 
   267 		for( i=0; i<info_ptr->num_palette; ++i ) {
   268 		    palette->colors[i].b = info_ptr->palette[i].blue;
   269 		    palette->colors[i].g = info_ptr->palette[i].green;
   270 		    palette->colors[i].r = info_ptr->palette[i].red;
   271 		}
   272 	    }
   273 	}
   274 
   275 done:	/* Clean up and return */
   276 	png_destroy_read_struct(&png_ptr, info_ptr ? &info_ptr : (png_infopp)0,
   277 								(png_infopp)0);
   278 	if ( row_pointers ) {
   279 		free(row_pointers);
   280 	}
   281 	return(surface); 
   282 }
   283 
   284 #else
   285 
   286 /* See if an image is contained in a data source */
   287 int IMG_isPNG(SDL_RWops *src)
   288 {
   289 	return(0);
   290 }
   291 
   292 /* Load a PNG type image from an SDL datasource */
   293 SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src)
   294 {
   295 	return(NULL);
   296 }
   297 
   298 #endif /* LOAD_PNG */