~extremepopcorn/dhlib/dhlib_ep

« back to all changes in this revision

Viewing changes to restricted/wordlib/src/writepng.cc

  • Committer: edA-qa mort-ora-y
  • Date: 2010-02-16 05:36:32 UTC
  • Revision ID: eda-qa@disemia.com-20100216053632-60lt7fndfi3fgblw
first

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#include <gd.h>
 
2
#include <cmath>
 
3
#include <cstdio>
 
4
#include <string>
 
5
#include <cassert>
 
6
#include <core/stdtypes.h>
 
7
 
 
8
void writePNG( const std::string& file, const _uint8* data, unsigned len )
 
9
{
 
10
        gdImagePtr im;
 
11
 
 
12
        //calculate a reasonable size
 
13
        unsigned width = (unsigned)sqrt( len ); 
 
14
        unsigned height = len / width + 1;
 
15
        
 
16
        im = gdImageCreate( width, height );
 
17
        for( unsigned i=0; i < 256; i++ )
 
18
                assert( gdImageColorAllocate( im, i ,i ,i ) == i );
 
19
                        
 
20
        //fill it in with data
 
21
        for( unsigned y = 0; y < height; y++ )
 
22
                for( unsigned x = 0; x < width; x++ )
 
23
                {
 
24
                        unsigned at = y * width + x;
 
25
                        if( at > len )
 
26
                                break;  //we're done now
 
27
                                
 
28
                        gdImageSetPixel( im, x, y, data[at] );
 
29
                }
 
30
                
 
31
        FILE* pngout = fopen( file.c_str(), "wb");
 
32
        gdImagePngEx(im, pngout, 9);
 
33
        fclose(pngout);
 
34
        
 
35
        gdImageDestroy(im);
 
36
}
 
37
 
 
38
_uint8* loadPNG( const std::string& file )
 
39
{
 
40
        FILE* pngin = fopen( file.c_str(), "rb" );
 
41
        
 
42
        gdImagePtr im = gdImageCreateFromPng( pngin );
 
43
        
 
44
        unsigned width = gdImageSX(im);
 
45
        unsigned height = gdImageSY(im);
 
46
        _uint8* data = new _uint8[ width * height ];
 
47
        for( unsigned y = 0; y < height; y++ )
 
48
                for( unsigned x = 0; x < width; x++ )
 
49
                {
 
50
                        unsigned at = y * width + x;
 
51
                        data[at] = gdImageGetPixel( im, x, y );
 
52
                }
 
53
        
 
54
        fclose( pngin );
 
55
        gdImageDestroy( im );
 
56
        
 
57
        return data;
 
58
}