File: ImageLib.cpp

package info (click to toggle)
libtuxcap 1.4.0.dfsg2-1.1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 4,172 kB
  • ctags: 5,897
  • sloc: cpp: 43,203; ansic: 3,095; python: 774; objc: 242; makefile: 100; xml: 87
file content (518 lines) | stat: -rw-r--r-- 14,549 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#define XMD_H

#include <Magick++.h>
#include "ImageLib.h"
#include <math.h>
#include "Common.h"
#include "SexyAppBase.h"

#if 0
#include <tchar.h>
#include "..\PakLib\PakInterface.h"
#endif

using namespace ImageLib;
using namespace Magick;

ImageLib::Image::Image()
{
	mWidth = 0;
	mHeight = 0;
	mBits = NULL;
}


ImageLib::Image::Image(int width, int height) {
  mWidth = width;
  mHeight = height;
  mBits = new uint32_t[mWidth * mHeight];
}


ImageLib::Image::~Image()
{
	delete[] mBits;
}

int	ImageLib::Image::GetWidth()
{
	return mWidth;
}

int	ImageLib::Image::GetHeight()
{
	return mHeight;
}

uint32_t* ImageLib::Image::GetBits()
{
	return mBits;
}

#if 0
//////////////////////////////////////////////////////////////////////////
// PNG Pak Support

static void png_pak_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
	png_size_t check;

	/* fread() returns 0 on error, so it is OK to store this in a png_size_t
	* instead of an int, which is what fread() actually returns.
	*/
	check = (png_size_t)p_fread(data, (png_size_t)1, length,
		(PFILE*)png_ptr->io_ptr);

	if (check != length)
	{
		png_error(png_ptr, "Read Error");
	}
}

bool ImageLib::WriteJPEGImage(const std::string& theFileName,ImageLib::Image* theImage)
{
	FILE *fp;

	if ((fp = fopen(theFileName.c_str(), "wb")) == NULL)
		return false;

	struct jpeg_compress_struct cinfo;
	struct my_error_mgr jerr;

	cinfo.err = jpeg_std_error(&jerr.pub);
	jerr.pub.error_exit = my_error_exit;

	if (setjmp(jerr.setjmp_buffer))
	{
		/* If we get here, the JPEG code has signaled an error.
		 * We need to clean up the JPEG object, close the input file, and return.
		 */
		jpeg_destroy_compress(&cinfo);
		fclose(fp);
		return false;
	}

	jpeg_create_compress(&cinfo);

	cinfo.image_width = theImage->mWidth;
	cinfo.image_height = theImage->mHeight;
	cinfo.input_components = 3;
    cinfo.in_color_space = JCS_RGB;
    cinfo.optimize_coding = 1;
    jpeg_set_defaults(&cinfo);
    jpeg_set_quality(&cinfo, 80, TRUE);

	jpeg_stdio_dest(&cinfo, fp);

	jpeg_start_compress(&cinfo, true);

	int row_stride = theImage->GetWidth() * 3;

	unsigned char* aTempBuffer = new unsigned char[row_stride];

	uint32_t* aSrcPtr = theImage->mBits;

	for (int aRow = 0; aRow < theImage->mHeight; aRow++)
	{
		unsigned char* aDest = aTempBuffer;

		for (int aCol = 0; aCol < theImage->mWidth; aCol++)
		{
			uint32_t src = *(aSrcPtr++);

			*aDest++ = (src >> 16) & 0xFF;
			*aDest++ = (src >>  8) & 0xFF;
			*aDest++ = (src      ) & 0xFF;
		}

		jpeg_write_scanlines(&cinfo, &aTempBuffer, 1);
	}

	delete [] aTempBuffer;

	jpeg_finish_compress(&cinfo);
	jpeg_destroy_compress(&cinfo);

	fclose(fp);

	return true;
}

boo ImageLib::WritePNGImage(const std::string& theFileName,ImageLib::Image* theImage)
{
	png_structp png_ptr;
	png_infop info_ptr;

	FILE *fp;

	if ((fp = fopen(theFileName.c_str(), "wb")) == NULL)
		return false;

	png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
	  NULL, NULL, NULL);

	if (png_ptr == NULL)
	{
		fclose(fp);
		return false;
	}

	// Allocate/initialize the memory for image information.  REQUIRED.
	info_ptr = png_create_info_struct(png_ptr);
	if (info_ptr == NULL)
	{
		fclose(fp);
		png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
		return false;
	}

   // Set error handling if you are using the setjmp/longjmp method (this is
   // the normal method of doing things with libpng).  REQUIRED unless you
   // set up your own error handlers in the png_create_write_struct() earlier.

	if (setjmp(png_ptr->jmpbuf))
	{
		// Free all of the memory associated with the png_ptr and info_ptr
		png_destroy_write_struct(&png_ptr, &info_ptr);
		fclose(fp);
		// If we get here, we had a problem writeing the file
		return NULL;
	}

	png_init_io(png_ptr, fp);

	png_color_8 sig_bit;
	sig_bit.red = 8;
	sig_bit.green = 8;
	sig_bit.blue = 8;
	/* if the image has an alpha channel then */
	sig_bit.alpha = 8;
	png_set_sBIT(png_ptr, info_ptr, &sig_bit);
	png_set_bgr(png_ptr);

	png_set_IHDR(png_ptr, info_ptr, theImage->mWidth, theImage->mHeight, 8, PNG_COLOR_TYPE_RGB_ALPHA,
       PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

	// Add filler (or alpha) byte (before/after each RGB triplet)
	//png_set_expand(png_ptr);
	//png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
	//png_set_gray_1_2_4_to_8(png_ptr);
	//png_set_palette_to_rgb(png_ptr);
	//png_set_gray_to_rgb(png_ptr);

	png_write_info(png_ptr, info_ptr);

	for (int i = 0; i < theImage->mHeight; i++)
	{
		png_bytep aRowPtr = (png_bytep) (theImage->mBits + i*theImage->mWidth);
		png_write_rows(png_ptr, &aRowPtr, 1);
	}

	// write rest of file, and get additional chunks in info_ptr - REQUIRED
	png_write_end(png_ptr, info_ptr);

	// clean up after the write, and free any memory allocated - REQUIRED
	png_destroy_write_struct(&png_ptr, &info_ptr);

	// close the file
	fclose(fp);

	return true;
}

bool ImageLib::WriteTGAImage(const std::string& theFileName,ImageLib::Image* theImage)
{
	FILE* aTGAFile = fopen(theFileName.c_str(), "wb");
	if (aTGAFile == NULL)
		return false;

	BYTE aHeaderIDLen = 0;
	fwrite(&aHeaderIDLen, sizeof(BYTE), 1, aTGAFile);

	BYTE aColorMapType = 0;
	fwrite(&aColorMapType, sizeof(BYTE), 1, aTGAFile);
	
	BYTE anImageType = 2;
	fwrite(&anImageType, sizeof(BYTE), 1, aTGAFile);

	WORD aFirstEntryIdx = 0;
	fwrite(&aFirstEntryIdx, sizeof(WORD), 1, aTGAFile);

	WORD aColorMapLen = 0;
	fwrite(&aColorMapLen, sizeof(WORD), 1, aTGAFile);

	BYTE aColorMapEntrySize = 0;
	fwrite(&aColorMapEntrySize, sizeof(BYTE), 1, aTGAFile);	

	WORD anXOrigin = 0;
	fwrite(&anXOrigin, sizeof(WORD), 1, aTGAFile);

	WORD aYOrigin = 0;
	fwrite(&aYOrigin, sizeof(WORD), 1, aTGAFile);

	WORD anImageWidth = theImage->mWidth;
	fwrite(&anImageWidth, sizeof(WORD), 1, aTGAFile);	

	WORD anImageHeight = theImage->mHeight;
	fwrite(&anImageHeight, sizeof(WORD), 1, aTGAFile);	

	BYTE aBitCount = 32;
	fwrite(&aBitCount, sizeof(BYTE), 1, aTGAFile);	

	BYTE anImageDescriptor = 8 | (1<<5);
	fwrite(&anImageDescriptor, sizeof(BYTE), 1, aTGAFile);

	fwrite(theImage->mBits, 4, theImage->mWidth*theImage->mHeight, aTGAFile);

	fclose(aTGAFile);

	return true;
}

bool ImageLib::WriteBMPImage(const std::string& theFileName,ImageLib::Image* theImage)
{
	FILE* aFile = fopen(theFileName.c_str(), "wb");
	if (aFile == NULL)
		return false;

	BITMAPFILEHEADER aFileHeader;
	BITMAPINFOHEADER aHeader;

	memset(&aFileHeader,0,sizeof(aFileHeader));
	memset(&aHeader,0,sizeof(aHeader));

	int aNumBytes = theImage->mWidth*theImage->mHeight*4;

	aFileHeader.bfType = ('M'<<8) | 'B';
	aFileHeader.bfSize = sizeof(aFileHeader) + sizeof(aHeader) + aNumBytes;
	aFileHeader.bfOffBits = sizeof(aHeader); 

	aHeader.biSize = sizeof(aHeader);
	aHeader.biWidth = theImage->mWidth;
	aHeader.biHeight = theImage->mHeight;
	aHeader.biPlanes = 1;
	aHeader.biBitCount = 32;
	aHeader.biCompression = BI_RGB;

	fwrite(&aFileHeader,sizeof(aFileHeader),1,aFile);
	fwrite(&aHeader,sizeof(aHeader),1,aFile);
	DWORD *aRow = theImage->mBits + (theImage->mHeight-1)*theImage->mWidth;
	int aRowSize = theImage->mWidth*4;
	for (int i=0; i<theImage->mHeight; i++, aRow-=theImage->mWidth)
		fwrite(aRow,4,theImage->mWidth,aFile);

	fclose(aFile);
	return true;
}

#endif

int ImageLib::gAlphaComposeColor = 0xFFFFFF;
bool ImageLib::gAutoLoadAlpha = true;
bool ImageLib::gIgnoreJPEG2000Alpha = true;

ImageLib::Image* ImageLib::GetImage(std::string theFilename, bool lookForAlphaImage)
{

	if (!gAutoLoadAlpha)
		lookForAlphaImage = false;

        theFilename = Sexy::ReplaceBackSlashes(theFilename);

	int aLastDotPos = theFilename.rfind('.');
	int aLastSlashPos = (int)theFilename.rfind('/');

	std::string anExt;
	std::string aFilename;

	if (aLastDotPos > aLastSlashPos)
	{
		anExt = theFilename.substr(aLastDotPos, theFilename.length() - aLastDotPos);
		aFilename = theFilename.substr(0, aLastDotPos);
	}
	else {
          aFilename = theFilename;
        
        }

        ImageLib::Image* anImage = NULL;

        Magick::Image mImage;
        bool ok = false;

        if (anExt.length() == 0) 
          {
            std::list<std::string> coderList;

            coderList.push_back("jpg");
            coderList.push_back("png");
            coderList.push_back("gif");
            coderList.push_back("jp2"); 
            coderList.push_back("tga");
            coderList.push_back("tif");
            coderList.push_back("bmp");

            std::list<std::string>::const_iterator entry = coderList.begin();
            while( entry != coderList.end() ) 
              {
                    try {
                        if (Sexy::gSexyAppBase->FileExists(theFilename + "." + *entry))  {
                          // Read a file into image object
                          mImage.read( theFilename + "." + *entry);
                          ok  = true;
                          break;
                        }
                        else if (Sexy::gSexyAppBase->FileExists(theFilename + "." + Sexy::Upper(*entry))) {
                          // Read a file into image object
                          mImage.read( theFilename + "." + Sexy::Upper(*entry));
                          ok  = true;
                          break;
                        }
                    }
                    catch( Magick::Exception &error_ )
                      {
                        return NULL;
                      }
                    catch (std::exception &error) {
                      return NULL;

                    }
                    catch ( ...) {
                      return NULL;
                    }
                ++entry;
              }
          }
        else
          {

            try {
              // Read a file into image object
              if (Sexy::gSexyAppBase->FileExists(theFilename)) {
                mImage.read( theFilename );
                ok = true;
              }
              else if (Sexy::gSexyAppBase->FileExists(aFilename + Sexy::Lower(anExt))) {
                mImage.read( aFilename + Sexy::Lower(anExt));
                ok = true;
              }
              else if (Sexy::gSexyAppBase->FileExists(aFilename + Sexy::Upper(anExt))) {
                mImage.read( aFilename + Sexy::Upper(anExt) );
                ok = true;
              }
            }
            catch( Magick::Exception &error_ )
              {
                return NULL;
              }
            catch (std::exception &error) {
              return NULL;
            }
            catch ( ...) {
              return NULL;
            }
          }
       
	// Check for alpha images
	Image* anAlphaImage = NULL;
	if(lookForAlphaImage)
	{
          // Check _ImageName
          anAlphaImage = GetImage(aFilename + "_", false);

          if(anAlphaImage==NULL) {
            anAlphaImage = GetImage(aFilename.substr(0, aLastSlashPos+1) + "_" +
                                    aFilename.substr(aLastSlashPos+1, aFilename.length() - aLastSlashPos - 1), false);
          }
	}

	// Compose alpha channel with image
	if (anAlphaImage != NULL) 
	{

          if (ok && anImage == NULL) {
            //TODO put this in a function
            anImage = new ImageLib::Image(mImage.baseColumns(), mImage.baseRows());

            const Magick::PixelPacket* pixels = mImage.getConstPixels(0,0,mImage.baseColumns(), mImage.baseRows());

            for(int i = 0; i < mImage.baseColumns() * mImage.baseRows(); ++i) {
              const Magick::PixelPacket* p = pixels + i;
              Magick::Color c(*p);
              Magick::ColorRGB rgb = c;

              *((unsigned char*)anImage->mBits + i * sizeof(uint32_t) + 2) = (unsigned char)(rgb.red() * 255.0f);          
              *((unsigned char*)anImage->mBits + i * sizeof(uint32_t) + 1) = (unsigned char)(rgb.green() * 255.0f);          
              *((unsigned char*)anImage->mBits + i * sizeof(uint32_t) + 0) = (unsigned char)(rgb.blue() * 255.0f);          
              *((unsigned char*)anImage->mBits + i * sizeof(uint32_t) + 3) = 255 - (unsigned char)(c.alpha() * 255.0f);
            }
          }

          if (anImage != NULL)
            {
              if ((anImage->mWidth == anAlphaImage->mWidth) &&
                  (anImage->mHeight == anAlphaImage->mHeight))
                {
                  uint32_t* aBits1 = anImage->mBits;
                  uint32_t* aBits2 = anAlphaImage->mBits;
                  int aSize = anImage->mWidth*anImage->mHeight;

                  for (int i = 0; i < aSize; i++)
                    {
                      *aBits1 = (*aBits1 & 0x00FFFFFF) | ((*aBits2 & 0xFF) << 24);
                      ++aBits1;
                      ++aBits2;
                    }
                }

              delete anAlphaImage;
            }
          else if (gAlphaComposeColor==0xFFFFFF)
            {
              anImage = anAlphaImage;

              uint32_t* aBits1 = anImage->mBits;

              int aSize = anImage->mWidth*anImage->mHeight;
              for (int i = 0; i < aSize; i++)
                {
                  *aBits1 = (0x00FFFFFF) | ((*aBits1 & 0xFF) << 24);
                  ++aBits1;
                }
            }
          else
            {
              const int aColor = gAlphaComposeColor;
              anImage = anAlphaImage;

              uint32_t* aBits1 = anImage->mBits;

              int aSize = anImage->mWidth*anImage->mHeight;
              for (int i = 0; i < aSize; i++)
                {
                  *aBits1 = aColor | ((*aBits1 & 0xFF) << 24);
                  ++aBits1;
                }
            }
	}

        if (anImage == NULL && ok) {
          anImage = new ImageLib::Image(mImage.baseColumns(), mImage.baseRows());

          const Magick::PixelPacket* pixels = mImage.getConstPixels(0,0,mImage.baseColumns(), mImage.baseRows());

          for(int i = 0; i < mImage.baseColumns() * mImage.baseRows(); ++i) {
            const Magick::PixelPacket* p = pixels + i;
            Magick::Color c(*p);
            Magick::ColorRGB rgb = c;

            *((unsigned char*)anImage->mBits + i * sizeof(uint32_t) + 2) = (unsigned char)(rgb.red() * 255.0f);          
            *((unsigned char*)anImage->mBits + i * sizeof(uint32_t) + 1) = (unsigned char)(rgb.green() * 255.0f);          
            *((unsigned char*)anImage->mBits + i * sizeof(uint32_t) + 0)= (unsigned char)(rgb.blue() * 255.0f);          
            *((unsigned char*)anImage->mBits + i * sizeof(uint32_t) + 3) = 255 - (unsigned char)(c.alpha() * 255.0f);
          }
        }

	return anImage;
}