| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
#include <stdlib.h> |
| 25 |
#include <png.h> |
| 26 |
#include "pngfuncs.h" |
| 27 |
|
| 28 |
|
| 29 |
static int png_colortype_from_surface(const SDL_Surface *surface) |
| 30 |
{ |
| 31 |
int colortype = PNG_COLOR_MASK_COLOR; |
| 32 |
|
| 33 |
if (surface->format->palette) |
| 34 |
colortype |= PNG_COLOR_MASK_PALETTE; |
| 35 |
else if (surface->format->Amask) |
| 36 |
colortype |= PNG_COLOR_MASK_ALPHA; |
| 37 |
|
| 38 |
return colortype; |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
void png_user_warn(png_structp ctx, png_const_charp str) |
| 43 |
{ |
| 44 |
fprintf(stderr, "libpng: warning: %s\n", str); |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
void png_user_error(png_structp ctx, png_const_charp str) |
| 49 |
{ |
| 50 |
fprintf(stderr, "libpng: error: %s\n", str); |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
int png_save_surface(const char *filename, const SDL_Surface *surf) |
| 55 |
{ |
| 56 |
FILE *fp; |
| 57 |
png_structp png_ptr; |
| 58 |
png_infop info_ptr; |
| 59 |
int i, colortype; |
| 60 |
png_bytep *row_pointers; |
| 61 |
|
| 62 |
|
| 63 |
fp = fopen(filename, "wb"); |
| 64 |
if (fp == NULL) { |
| 65 |
perror("fopen error"); |
| 66 |
return -1; |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, |
| 71 |
NULL, png_user_error, png_user_warn); |
| 72 |
if (png_ptr == NULL) { |
| 73 |
printf("png_create_write_struct error!\n"); |
| 74 |
return -1; |
| 75 |
} |
| 76 |
|
| 77 |
info_ptr = png_create_info_struct(png_ptr); |
| 78 |
if (info_ptr == NULL) { |
| 79 |
png_destroy_write_struct(&png_ptr, (png_infopp)NULL); |
| 80 |
printf("png_create_info_struct error!\n"); |
| 81 |
exit(-1); |
| 82 |
} |
| 83 |
|
| 84 |
if (setjmp(png_jmpbuf(png_ptr))) { |
| 85 |
png_destroy_write_struct(&png_ptr, &info_ptr); |
| 86 |
fclose(fp); |
| 87 |
exit(-1); |
| 88 |
} |
| 89 |
|
| 90 |
png_init_io(png_ptr, fp); |
| 91 |
|
| 92 |
colortype = png_colortype_from_surface(surf); |
| 93 |
png_set_IHDR(png_ptr, info_ptr, surf->w, surf->h, 8, colortype, PNG_INTERLACE_NONE, |
| 94 |
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); |
| 95 |
|
| 96 |
|
| 97 |
png_write_info(png_ptr, info_ptr); |
| 98 |
png_set_packing(png_ptr); |
| 99 |
|
| 100 |
row_pointers = (png_bytep*) malloc(sizeof(png_bytep)*surf->h); |
| 101 |
for (i = 0; i < surf->h; i++) |
| 102 |
row_pointers[i] = (png_bytep)(Uint8 *)surf->pixels + i*surf->pitch; |
| 103 |
png_write_image(png_ptr, row_pointers); |
| 104 |
png_write_end(png_ptr, info_ptr); |
| 105 |
|
| 106 |
|
| 107 |
free(row_pointers); |
| 108 |
png_destroy_write_struct(&png_ptr, &info_ptr); |
| 109 |
fclose(fp); |
| 110 |
|
| 111 |
return 0; |
| 112 |
} |