00001
00002
00003
00004 #include <fstream>
00005 #include "utils.h"
00006 #include "tga_image.h"
00007
00009 image::image_t*
00010 image::tga::load( const std::string& filename )
00011 {
00012
00013 std::ifstream stream( filename.c_str( ) );
00014 if( !stream ) {
00015
00016 return NULL;
00017 }
00018
00019
00020 image_t* img = load( stream );
00021
00022
00023 stream.close( );
00024
00025
00026 return img;
00027 }
00028
00030 image::image_t*
00031 image::tga::load( std::istream& stream )
00032 {
00033
00034 header_t header;
00035 if( !utils::read( stream, header ) ) {
00036
00037 return NULL;
00038 }
00039
00040
00041 if( (header.id_length != 0) ||
00042 (header.color_map_type != 0) ||
00043 (header.image_type != 2) ||
00044 (header.x_origin != 0) ||
00045 (header.y_origin != 0) ) {
00046
00047 return false;
00048 }
00049
00050
00051 image_t::format format;
00052 if( header.bpp == 24 ) {
00053 format = image_t::RGB;
00054 } else if( header.bpp == 32 ) {
00055 format = image_t::RGBA;
00056 }
00057
00058
00059 image_t *img = new image_t( header.width, header.height, format,
00060 image_t::BYTE );
00061 img->seek( 0, 0 );
00062
00063
00064 unsigned int pixels = header.width * header.height;
00065
00066 if( format == image_t::RGB ) {
00067 char r, g, b;
00068 for( unsigned int i = 0; i < pixels; ++i ) {
00069 if( !(stream.read( &b, 1 ) &&
00070 stream.read( &g, 1 ) &&
00071 stream.read( &r, 1 )) ) {
00072
00073 delete img;
00074 return NULL;
00075 }
00076
00077
00078 img->write( r, g, b );
00079 }
00080 } else {
00081 char r, g, b, a;
00082 for( unsigned int i = 0; i < pixels; ++i ) {
00083 if( !(stream.read( &b, 1 ) &&
00084 stream.read( &g, 1 ) &&
00085 stream.read( &r, 1 ) &&
00086 stream.read( &a, 1 )) ) {
00087
00088 delete img;
00089 return NULL;
00090 }
00091
00092
00093 img->write( r, g, b, a );
00094 }
00095 }
00096
00097 return img;
00098
00099 }
00100
00102 bool
00103 image::tga::can_load( const std::string& filename )
00104 {
00105
00106 std::ifstream stream( filename.c_str( ) );
00107 if( !stream ) {
00108
00109 return false;
00110 }
00111
00112
00113 bool loadable = can_load( stream );
00114
00115
00116 stream.close( );
00117
00118
00119 return loadable;
00120 }
00121
00123 bool
00124 image::tga::can_load( std::istream& stream )
00125 {
00126
00127 std::streampos save = stream.tellg( );
00128
00129
00130 header_t header;
00131 if( !utils::read( stream, header ) ) {
00132
00133
00134 stream.seekg( save );
00135 return false;
00136 }
00137
00138
00139 stream.seekg( save );
00140
00141
00142 if( (header.id_length != 0) ||
00143 (header.color_map_type != 0) ||
00144 (header.image_type != 2) ||
00145 (header.x_origin != 0) ||
00146 (header.y_origin != 0) ) {
00147
00148 return false;
00149 }
00150
00151
00152 return true;
00153 }