root/OpenSceneGraph/trunk/src/osgPlugins/png/ReaderWriterPNG.cpp @ 11121

Revision 11121, 13.8 kB (checked in by robert, 3 years ago)

From Philip Lownman, "The libpng project decided to rename png_set_gray_1_2_4_to_8() to
png_set_expand_gray_1_2_4_to_8() with the 1.2.9 release. This
submission fixes builds of the OSG against versions of libpng < 1.2.9
that don't have the new symbol available. This affects platforms like
Red Hat Enterprise Linux 4 which come with libpng 1.2.7."

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osg/Image>
2#include <osg/Notify>
3#include <osg/Geode>
4#include <osg/GL>
5#include <osg/Endian>
6
7#include <osgDB/Registry>
8#include <osgDB/FileUtils>
9#include <osgDB/FileNameUtils>
10
11#include <sstream>
12
13using namespace osg;
14
15extern "C"
16{
17    #include <zlib.h>
18    #include <png.h>
19}
20
21
22/* Transparency parameters */
23#define PNG_ALPHA     -2         /* Use alpha channel in PNG file, if there is one */
24#define PNG_SOLID     -1         /* No transparency                                */
25#define PNG_STENCIL    0         /* Sets alpha to 0 for r=g=b=0, 1 otherwise       */
26
27typedef struct
28{
29    unsigned int Width;
30    unsigned int Height;
31    unsigned int Depth;
32    unsigned int Alpha;
33} pngInfo;
34
35class PNGError
36{
37public:
38    PNGError(const char* message)
39    {
40        _message = "PNG lib error : ";
41        _message += message;
42    }
43    friend std::ostream& operator<<(std::ostream& stream, const PNGError& err)
44    {
45        stream << err._message;
46        return stream;
47    }
48private:
49    std::string _message;
50};
51
52void user_error_fn(png_structp png_ptr, png_const_charp error_msg)
53{
54#ifdef OSG_CPP_EXCEPTIONS_AVAILABLE
55    throw PNGError(error_msg);
56#else
57    osg::notify(osg::WARN) << "PNG lib warning : " << error_msg << std::endl;
58#endif
59}
60
61void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg)
62{
63    osg::notify(osg::WARN) << "PNG lib warning : " << warning_msg << std::endl;
64}
65
66void png_read_istream(png_structp png_ptr, png_bytep data, png_size_t length)
67{
68    std::istream *stream = (std::istream*)png_get_io_ptr(png_ptr); //Get pointer to istream
69    stream->read((char*)data,length); //Read requested amount of data
70}
71
72void png_write_ostream(png_structp png_ptr, png_bytep data, png_size_t length)
73{
74    std::ostream *stream = (std::ostream*)png_get_io_ptr(png_ptr); //Get pointer to ostream
75    stream->write((char*)data,length); //Write requested amount of data
76}
77
78void png_flush_ostream(png_structp png_ptr)
79{
80    std::ostream *stream = (std::ostream*)png_get_io_ptr(png_ptr); //Get pointer to ostream
81    stream->flush();
82}
83
84class ReaderWriterPNG : public osgDB::ReaderWriter
85{
86    public:
87        ReaderWriterPNG()
88        {
89            supportsExtension("png","PNG Image format");
90        }
91       
92        virtual const char* className() const { return "PNG Image Reader/Writer"; }
93
94        WriteResult::WriteStatus writePngStream(std::ostream& fout, const osg::Image& img, int compression_level) const
95        {
96            png_structp png = NULL;
97            png_infop   info = NULL;
98            int color;
99            png_bytep *rows = NULL;
100
101            //Create write structure
102            png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
103            if(!png) return WriteResult::ERROR_IN_WRITING_FILE;
104
105            //Create infr structure
106            info = png_create_info_struct(png);
107            if(!info) return WriteResult::ERROR_IN_WRITING_FILE;
108
109            //Set custom write function so it will write to ostream
110            png_set_write_fn(png,&fout,png_write_ostream,png_flush_ostream);
111
112            //Set compression level
113            png_set_compression_level(png, compression_level);
114
115            switch(img.getPixelFormat()) {
116                case(GL_LUMINANCE): color = PNG_COLOR_TYPE_GRAY; break;
117                case(GL_ALPHA): color = PNG_COLOR_TYPE_GRAY; break; //Couldn't find a color type for pure alpha, using gray instead
118                case(GL_LUMINANCE_ALPHA): color = PNG_COLOR_TYPE_GRAY_ALPHA ; break;
119                case(GL_RGB): color = PNG_COLOR_TYPE_RGB; break;
120                case(GL_RGBA): color = PNG_COLOR_TYPE_RGB_ALPHA; break;
121                default: return WriteResult::ERROR_IN_WRITING_FILE; break;               
122            }
123
124            //Create row data
125            rows = new png_bytep[img.t()];
126            for(int i = 0; i < img.t(); ++i) {
127                rows[i] = (png_bytep)img.data(0,img.t() - i - 1);
128            }
129
130            //Write header info
131            png_set_IHDR(png, info, img.s(), img.t(),
132                        8, color, PNG_INTERLACE_NONE,
133                        PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
134
135            png_write_info(png, info);
136
137            //Write data
138            png_write_image(png, rows);
139
140            //End write
141            png_write_end(png, NULL);
142
143            //Cleanup
144            png_destroy_write_struct(&png,&info);
145            delete [] rows;
146
147            return WriteResult::FILE_SAVED;
148        }
149
150        ReadResult readPNGStream(std::istream& fin) const
151        {
152            int trans = PNG_ALPHA;
153            pngInfo pInfo;
154            pngInfo *pinfo = &pInfo;
155
156            unsigned char header[8];
157            png_structp png;
158            png_infop   info;
159            png_infop   endinfo;
160            png_bytep   data;    //, data2;
161            png_bytep  *row_p;
162            double  fileGamma;
163
164            png_uint_32 width, height;
165            int depth, color;
166
167            png_uint_32 i;
168            png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
169 
170            // Set custom error handlers
171            png_set_error_fn(png, png_get_error_ptr(png), user_error_fn, user_warning_fn);
172
173            #ifdef OSG_CPP_EXCEPTIONS_AVAILABLE
174            try
175            #endif
176            {
177                info = png_create_info_struct(png);
178                endinfo = png_create_info_struct(png);
179
180                fin.read((char*)header,8);
181                if (fin.gcount() == 8 && png_sig_cmp(header, 0, 8) == 0)
182                    png_set_read_fn(png,&fin,png_read_istream); //Use custom read function that will get data from istream
183                else
184                {
185                    png_destroy_read_struct(&png, &info, &endinfo);
186                    return ReadResult::FILE_NOT_HANDLED;
187                }
188                png_set_sig_bytes(png, 8);
189
190                png_read_info(png, info);
191                png_get_IHDR(png, info, &width, &height, &depth, &color, NULL, NULL, NULL);
192
193                if (pinfo != NULL)
194                {
195                    pinfo->Width  = width;
196                    pinfo->Height = height;
197                    pinfo->Depth  = depth;
198                }
199
200                osg::notify(osg::INFO)<<"width="<<width<<" height="<<height<<" depth="<<depth<<std::endl;
201                if ( color == PNG_COLOR_TYPE_RGB) osg::notify(osg::INFO) << "color == PNG_COLOR_TYPE_RGB "<<std::endl;
202                if ( color == PNG_COLOR_TYPE_GRAY) osg::notify(osg::INFO) << "color == PNG_COLOR_TYPE_GRAY "<<std::endl;
203                if ( color == PNG_COLOR_TYPE_GRAY_ALPHA) osg::notify(osg::INFO) << "color ==  PNG_COLOR_TYPE_GRAY_ALPHA"<<std::endl;
204
205                // png default to big endian, so we'll need to swap bytes if on a little endian machine.
206                if (depth>8 && getCpuByteOrder()==osg::LittleEndian)
207                    png_set_swap(png);
208
209
210                if (color == PNG_COLOR_TYPE_GRAY || color == PNG_COLOR_TYPE_GRAY_ALPHA)
211                {
212                    //png_set_gray_to_rgb(png);
213                }
214
215                if (color&PNG_COLOR_MASK_ALPHA && trans != PNG_ALPHA)
216                {
217                    png_set_strip_alpha(png);
218                    color &= ~PNG_COLOR_MASK_ALPHA;
219                }
220
221
222
223                //    if (!(PalettedTextures && mipmap >= 0 && trans == PNG_SOLID))
224                //if (color == PNG_COLOR_TYPE_PALETTE)
225                //    png_set_expand(png);
226
227                // In addition to expanding the palette, we also need to check
228                // to expand greyscale and alpha images.  See libpng man page.
229                if (color == PNG_COLOR_TYPE_PALETTE)
230                    png_set_palette_to_rgb(png);
231                if (color == PNG_COLOR_TYPE_GRAY && depth < 8)
232                {
233                #if PNG_LIBPNG_VER >= 10209
234                    png_set_expand_gray_1_2_4_to_8(png);
235                #else
236                    // use older now deprecated but identical call
237                    png_set_gray_1_2_4_to_8(png);
238                #endif
239                }
240                if (png_get_valid(png, info, PNG_INFO_tRNS))
241                    png_set_tRNS_to_alpha(png);
242
243                // Make sure that files of small depth are packed properly.
244                if (depth < 8)
245                    png_set_packing(png);
246
247
248                /*--GAMMA--*/
249                //    checkForGammaEnv();
250                double screenGamma = 2.2 / 1.0;
251                if (png_get_gAMA(png, info, &fileGamma))
252                    png_set_gamma(png, screenGamma, fileGamma);
253                else
254                    png_set_gamma(png, screenGamma, 1.0/2.2);
255
256                png_read_update_info(png, info);
257
258                data = (png_bytep) new unsigned char [png_get_rowbytes(png, info)*height];
259                row_p = new png_bytep [height];
260
261                bool StandardOrientation = true;
262                for (i = 0; i < height; i++)
263                {
264                    if (StandardOrientation)
265                        row_p[height - 1 - i] = &data[png_get_rowbytes(png, info)*i];
266                    else
267                        row_p[i] = &data[png_get_rowbytes(png, info)*i];
268                }
269
270                png_read_image(png, row_p);
271                delete [] row_p;
272                png_read_end(png, endinfo);
273
274                GLenum pixelFormat = 0;
275                GLenum dataType = depth<=8?GL_UNSIGNED_BYTE:GL_UNSIGNED_SHORT;
276                switch(color)
277                {
278                  case(PNG_SOLID): pixelFormat = GL_LUMINANCE; break;
279                  case(PNG_ALPHA): pixelFormat = GL_ALPHA; break;
280                  case(PNG_COLOR_TYPE_GRAY): pixelFormat =GL_LUMINANCE ; break;
281                  case(PNG_COLOR_TYPE_GRAY_ALPHA): pixelFormat = GL_LUMINANCE_ALPHA; break;
282                  case(PNG_COLOR_TYPE_RGB): pixelFormat = GL_RGB; break;
283                  case(PNG_COLOR_TYPE_PALETTE): pixelFormat = GL_RGB; break;
284                  case(PNG_COLOR_TYPE_RGB_ALPHA): pixelFormat = GL_RGBA; break;
285                  default: break;               
286                }
287
288                // Some paletted images contain alpha information.  To be
289                // able to give that back to the calling program, we need to
290                // check the number of channels in the image.  However, the
291                // call might not return correct information unless
292                // png_read_end is called first.  See libpng man page.
293                if (pixelFormat == GL_RGB && png_get_channels(png, info) == 4)
294                    pixelFormat = GL_RGBA;
295
296                int internalFormat = pixelFormat;
297
298                png_destroy_read_struct(&png, &info, &endinfo);
299
300                //    delete [] data;
301
302                if (pixelFormat==0)
303                    return ReadResult::FILE_NOT_HANDLED;
304
305                osg::Image* pOsgImage = new osg::Image();
306
307                pOsgImage->setImage(width, height, 1,
308                    internalFormat,
309                    pixelFormat,
310                    dataType,
311                    data,
312                    osg::Image::USE_NEW_DELETE);
313
314                return pOsgImage;
315
316            }
317            #ifdef OSG_CPP_EXCEPTIONS_AVAILABLE
318            catch (PNGError& err)
319            {
320                osg::notify(osg::WARN) << err << std::endl;
321                png_destroy_read_struct(&png, &info, &endinfo);
322                return ReadResult::ERROR_IN_READING_FILE;
323            }
324            #endif
325        }
326
327        int getCompressionLevel(const osgDB::ReaderWriter::Options *options) const
328        {
329            if(options) {
330                std::istringstream iss(options->getOptionString());
331                std::string opt;
332                while (iss >> opt) {
333                    if(opt=="PNG_COMPRESSION") {
334                        int level;
335                        iss >> level;
336                        return level;
337                    }
338                }
339            }
340
341            return Z_DEFAULT_COMPRESSION;
342        }
343
344        virtual ReadResult readObject(std::istream& fin,const osgDB::ReaderWriter::Options* options =NULL) const
345        {
346            return readImage(fin, options);
347        }
348
349        virtual ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options =NULL) const
350        {
351            return readImage(file, options);
352        }
353
354        virtual ReadResult readImage(std::istream& fin,const Options* =NULL) const
355        {
356            return readPNGStream(fin);
357        }
358
359        virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const
360        {
361            std::string ext = osgDB::getLowerCaseFileExtension(file);
362            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
363
364            std::string fileName = osgDB::findDataFile( file, options );
365            if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
366
367            std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary);
368            if(!istream) return ReadResult::FILE_NOT_HANDLED;
369            ReadResult rr = readPNGStream(istream);
370            if(rr.validImage()) rr.getImage()->setFileName(file);
371            return rr;
372        }
373
374        virtual WriteResult writeImage(const osg::Image& img,std::ostream& fout,const osgDB::ReaderWriter::Options *options) const
375        {
376            WriteResult::WriteStatus ws = writePngStream(fout,img,getCompressionLevel(options));
377            return ws;
378        }
379
380        virtual WriteResult writeImage(const osg::Image &img,const std::string& fileName, const osgDB::ReaderWriter::Options *options) const
381        {
382            std::string ext = osgDB::getFileExtension(fileName);
383            if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
384
385            std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);
386            if(!fout) return WriteResult::ERROR_IN_WRITING_FILE;
387
388            return writeImage(img,fout,options);
389        }
390};
391
392// now register with Registry to instantiate the above
393// reader/writer.
394REGISTER_OSGPLUGIN(png, ReaderWriterPNG)
Note: See TracBrowser for help on using the browser.