00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015 #include "mximage.h"
00016
00017
00018 namespace mx
00019 {
00020
00021 SDL_Surface *mxImage::loadIMG(string filename) {
00022
00023 std::string prefix = filename.substr(filename.rfind(".")+1, filename.length() - filename.rfind(".")-1 );
00024
00025 unsigned int i;
00026 for(i = 0; i < prefix.length(); i++) prefix[i] = tolower(prefix[i]);
00027
00028 if(prefix == "bmp")
00029 return SDL_LoadBMP(filename.c_str());
00030
00031 else if(prefix == "jpg" || prefix == "jpeg") {
00032
00033 mx::mxJpeg j;
00034 if( j.jpgOpen(filename) == false ) return 0;
00035 SDL_Surface *surf = j.LoadJPG();
00036 j.jpgClose();
00037 return surf;
00038 }
00039
00040 else if(prefix == "png") {
00041 mx::mxPng p;
00042
00043 if( p.pngOpen(filename) == false ) return 0;
00044 SDL_Surface *surf = p.LoadPNG();
00045 p.pngClose();
00046 return surf;
00047 }
00048
00049 return 0;
00050
00051 }
00052
00053
00054 bool mxImage::loadIMG(mx::mxSurface &surf, string filename) {
00055
00056 SDL_Surface *surface = loadIMG(filename);
00057 if(surface == 0) return false;
00058 surf = surface;
00059 return true;
00060 }
00061
00062 void mxImage::saveJPG(SDL_Surface *surf, string filename) {
00063
00064 jpeg_compress_struct comp_info;
00065 jpeg_error_mgr jerr;
00066
00067 JSAMPROW row_ptr[1];
00068
00069 FILE *fptr = fopen(filename.c_str(), "w");
00070 if(!fptr) return;
00071
00072 comp_info.err = jpeg_std_error(&jerr);
00073 jpeg_create_compress(&comp_info);
00074 jpeg_stdio_dest(&comp_info, fptr);
00075
00076 comp_info.image_width = surf->w;
00077 comp_info.image_height = surf->h;
00078 comp_info.input_components = 3;
00079 comp_info.in_color_space = JCS_RGB;
00080
00081 jpeg_set_defaults(&comp_info);
00082 jpeg_start_compress(&comp_info, TRUE);
00083
00084
00085
00086 if(SDL_MUSTLOCK(surf)) SDL_LockSurface(surf);
00087
00088
00089 unsigned char *buffer = (unsigned char*) calloc (1, surf->w * surf->h * 3 );
00090 unsigned int counter = 0;
00091
00092 unsigned char *ptr = buffer;
00093 unsigned char *pix = (unsigned char*)surf->pixels;
00094
00095 while(counter < (surf->w*surf->h)) {
00096
00097
00098 unsigned int *ptr_val = (unsigned int *) pix;
00099 SDL_GetRGB(*ptr_val, surf->format, &ptr[0], &ptr[1], &ptr[2]);
00100 pix += surf->format->BytesPerPixel;
00101 ptr += 3;
00102 counter++;
00103 }
00104
00105 while( comp_info.next_scanline < comp_info.image_height ) {
00106 row_ptr[0] = &buffer[ comp_info.next_scanline * comp_info.image_width * comp_info.input_components];
00107 jpeg_write_scanlines (&comp_info, row_ptr, 1);
00108 }
00109
00110
00111 free(buffer);
00112
00113
00114 if(SDL_MUSTLOCK(surf)) SDL_UnlockSurface(surf);
00115
00116 jpeg_finish_compress(&comp_info);
00117 jpeg_destroy_compress(&comp_info);
00118 fclose(fptr);
00119
00120 }
00121
00122 }
00123
00124
00125
00126