Correct wxImage::Size() again; add unit tests for it.
[wxWidgets.git] / src / common / image.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/image.cpp
3 // Purpose: wxImage
4 // Author: Robert Roebling
5 // RCS-ID: $Id$
6 // Copyright: (c) Robert Roebling
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
12
13 #ifdef __BORLANDC__
14 #pragma hdrstop
15 #endif
16
17 #if wxUSE_IMAGE
18
19 #include "wx/image.h"
20
21 #ifndef WX_PRECOMP
22 #include "wx/log.h"
23 #include "wx/hash.h"
24 #include "wx/utils.h"
25 #include "wx/math.h"
26 #include "wx/module.h"
27 #include "wx/palette.h"
28 #include "wx/intl.h"
29 #endif
30
31 #include "wx/filefn.h"
32 #include "wx/wfstream.h"
33 #include "wx/xpmdecod.h"
34
35 // For memcpy
36 #include <string.h>
37
38 // make the code compile with either wxFile*Stream or wxFFile*Stream:
39 #define HAS_FILE_STREAMS (wxUSE_STREAMS && (wxUSE_FILE || wxUSE_FFILE))
40
41 #if HAS_FILE_STREAMS
42 #if wxUSE_FFILE
43 typedef wxFFileInputStream wxImageFileInputStream;
44 typedef wxFFileOutputStream wxImageFileOutputStream;
45 #elif wxUSE_FILE
46 typedef wxFileInputStream wxImageFileInputStream;
47 typedef wxFileOutputStream wxImageFileOutputStream;
48 #endif // wxUSE_FILE/wxUSE_FFILE
49 #endif // HAS_FILE_STREAMS
50
51 #if wxUSE_VARIANT
52 IMPLEMENT_VARIANT_OBJECT_EXPORTED_SHALLOWCMP(wxImage,WXDLLEXPORT)
53 #endif
54
55 //-----------------------------------------------------------------------------
56 // global data
57 //-----------------------------------------------------------------------------
58
59 wxList wxImage::sm_handlers;
60 wxImage wxNullImage;
61
62 //-----------------------------------------------------------------------------
63 // wxImageRefData
64 //-----------------------------------------------------------------------------
65
66 class wxImageRefData: public wxObjectRefData
67 {
68 public:
69 wxImageRefData();
70 virtual ~wxImageRefData();
71
72 int m_width;
73 int m_height;
74 wxBitmapType m_type;
75 unsigned char *m_data;
76
77 bool m_hasMask;
78 unsigned char m_maskRed,m_maskGreen,m_maskBlue;
79
80 // alpha channel data, may be NULL for the formats without alpha support
81 unsigned char *m_alpha;
82
83 bool m_ok;
84
85 // if true, m_data is pointer to static data and shouldn't be freed
86 bool m_static;
87
88 // same as m_static but for m_alpha
89 bool m_staticAlpha;
90
91 #if wxUSE_PALETTE
92 wxPalette m_palette;
93 #endif // wxUSE_PALETTE
94
95 wxArrayString m_optionNames;
96 wxArrayString m_optionValues;
97
98 wxDECLARE_NO_COPY_CLASS(wxImageRefData);
99 };
100
101 wxImageRefData::wxImageRefData()
102 {
103 m_width = 0;
104 m_height = 0;
105 m_type = wxBITMAP_TYPE_INVALID;
106 m_data =
107 m_alpha = (unsigned char *) NULL;
108
109 m_maskRed = 0;
110 m_maskGreen = 0;
111 m_maskBlue = 0;
112 m_hasMask = false;
113
114 m_ok = false;
115 m_static =
116 m_staticAlpha = false;
117 }
118
119 wxImageRefData::~wxImageRefData()
120 {
121 if ( !m_static )
122 free( m_data );
123 if ( !m_staticAlpha )
124 free( m_alpha );
125 }
126
127
128 //-----------------------------------------------------------------------------
129 // wxImage
130 //-----------------------------------------------------------------------------
131
132 #define M_IMGDATA static_cast<wxImageRefData*>(m_refData)
133
134 IMPLEMENT_DYNAMIC_CLASS(wxImage, wxObject)
135
136 bool wxImage::Create(const char* const* xpmData)
137 {
138 #if wxUSE_XPM
139 UnRef();
140
141 wxXPMDecoder decoder;
142 (*this) = decoder.ReadData(xpmData);
143 return Ok();
144 #else
145 return false;
146 #endif
147 }
148
149 bool wxImage::Create( int width, int height, bool clear )
150 {
151 UnRef();
152
153 m_refData = new wxImageRefData();
154
155 M_IMGDATA->m_data = (unsigned char *) malloc( width*height*3 );
156 if (!M_IMGDATA->m_data)
157 {
158 UnRef();
159 return false;
160 }
161
162 M_IMGDATA->m_width = width;
163 M_IMGDATA->m_height = height;
164 M_IMGDATA->m_ok = true;
165
166 if (clear)
167 {
168 Clear();
169 }
170
171 return true;
172 }
173
174 bool wxImage::Create( int width, int height, unsigned char* data, bool static_data )
175 {
176 UnRef();
177
178 wxCHECK_MSG( data, false, wxT("NULL data in wxImage::Create") );
179
180 m_refData = new wxImageRefData();
181
182 M_IMGDATA->m_data = data;
183 M_IMGDATA->m_width = width;
184 M_IMGDATA->m_height = height;
185 M_IMGDATA->m_ok = true;
186 M_IMGDATA->m_static = static_data;
187
188 return true;
189 }
190
191 bool wxImage::Create( int width, int height, unsigned char* data, unsigned char* alpha, bool static_data )
192 {
193 UnRef();
194
195 wxCHECK_MSG( data, false, wxT("NULL data in wxImage::Create") );
196
197 m_refData = new wxImageRefData();
198
199 M_IMGDATA->m_data = data;
200 M_IMGDATA->m_alpha = alpha;
201 M_IMGDATA->m_width = width;
202 M_IMGDATA->m_height = height;
203 M_IMGDATA->m_ok = true;
204 M_IMGDATA->m_static = static_data;
205 M_IMGDATA->m_staticAlpha = static_data;
206
207 return true;
208 }
209
210 void wxImage::Destroy()
211 {
212 UnRef();
213 }
214
215 void wxImage::Clear(unsigned char value)
216 {
217 memset(M_IMGDATA->m_data, value, M_IMGDATA->m_width*M_IMGDATA->m_height*3);
218 }
219
220 wxObjectRefData* wxImage::CreateRefData() const
221 {
222 return new wxImageRefData;
223 }
224
225 wxObjectRefData* wxImage::CloneRefData(const wxObjectRefData* that) const
226 {
227 const wxImageRefData* refData = static_cast<const wxImageRefData*>(that);
228 wxCHECK_MSG(refData->m_ok, NULL, wxT("invalid image") );
229
230 wxImageRefData* refData_new = new wxImageRefData;
231 refData_new->m_width = refData->m_width;
232 refData_new->m_height = refData->m_height;
233 refData_new->m_maskRed = refData->m_maskRed;
234 refData_new->m_maskGreen = refData->m_maskGreen;
235 refData_new->m_maskBlue = refData->m_maskBlue;
236 refData_new->m_hasMask = refData->m_hasMask;
237 refData_new->m_ok = true;
238 unsigned size = unsigned(refData->m_width) * unsigned(refData->m_height);
239 if (refData->m_alpha != NULL)
240 {
241 refData_new->m_alpha = (unsigned char*)malloc(size);
242 memcpy(refData_new->m_alpha, refData->m_alpha, size);
243 }
244 size *= 3;
245 refData_new->m_data = (unsigned char*)malloc(size);
246 memcpy(refData_new->m_data, refData->m_data, size);
247 #if wxUSE_PALETTE
248 refData_new->m_palette = refData->m_palette;
249 #endif
250 refData_new->m_optionNames = refData->m_optionNames;
251 refData_new->m_optionValues = refData->m_optionValues;
252 return refData_new;
253 }
254
255 wxImage wxImage::Copy() const
256 {
257 wxImage image;
258
259 wxCHECK_MSG( Ok(), image, wxT("invalid image") );
260
261 image.m_refData = CloneRefData(m_refData);
262
263 return image;
264 }
265
266 wxImage wxImage::ShrinkBy( int xFactor , int yFactor ) const
267 {
268 if( xFactor == 1 && yFactor == 1 )
269 return *this;
270
271 wxImage image;
272
273 wxCHECK_MSG( Ok(), image, wxT("invalid image") );
274
275 // can't scale to/from 0 size
276 wxCHECK_MSG( (xFactor > 0) && (yFactor > 0), image,
277 wxT("invalid new image size") );
278
279 long old_height = M_IMGDATA->m_height,
280 old_width = M_IMGDATA->m_width;
281
282 wxCHECK_MSG( (old_height > 0) && (old_width > 0), image,
283 wxT("invalid old image size") );
284
285 long width = old_width / xFactor ;
286 long height = old_height / yFactor ;
287
288 image.Create( width, height, false );
289
290 char unsigned *data = image.GetData();
291
292 wxCHECK_MSG( data, image, wxT("unable to create image") );
293
294 bool hasMask = false ;
295 unsigned char maskRed = 0;
296 unsigned char maskGreen = 0;
297 unsigned char maskBlue =0 ;
298
299 unsigned char *source_data = M_IMGDATA->m_data;
300 unsigned char *target_data = data;
301 unsigned char *source_alpha = 0 ;
302 unsigned char *target_alpha = 0 ;
303 if (M_IMGDATA->m_hasMask)
304 {
305 hasMask = true ;
306 maskRed = M_IMGDATA->m_maskRed;
307 maskGreen = M_IMGDATA->m_maskGreen;
308 maskBlue =M_IMGDATA->m_maskBlue ;
309
310 image.SetMaskColour( M_IMGDATA->m_maskRed,
311 M_IMGDATA->m_maskGreen,
312 M_IMGDATA->m_maskBlue );
313 }
314 else
315 {
316 source_alpha = M_IMGDATA->m_alpha ;
317 if ( source_alpha )
318 {
319 image.SetAlpha() ;
320 target_alpha = image.GetAlpha() ;
321 }
322 }
323
324 for (long y = 0; y < height; y++)
325 {
326 for (long x = 0; x < width; x++)
327 {
328 unsigned long avgRed = 0 ;
329 unsigned long avgGreen = 0;
330 unsigned long avgBlue = 0;
331 unsigned long avgAlpha = 0 ;
332 unsigned long counter = 0 ;
333 // determine average
334 for ( int y1 = 0 ; y1 < yFactor ; ++y1 )
335 {
336 long y_offset = (y * yFactor + y1) * old_width;
337 for ( int x1 = 0 ; x1 < xFactor ; ++x1 )
338 {
339 unsigned char *pixel = source_data + 3 * ( y_offset + x * xFactor + x1 ) ;
340 unsigned char red = pixel[0] ;
341 unsigned char green = pixel[1] ;
342 unsigned char blue = pixel[2] ;
343 unsigned char alpha = 255 ;
344 if ( source_alpha )
345 alpha = *(source_alpha + y_offset + x * xFactor + x1) ;
346 if ( !hasMask || red != maskRed || green != maskGreen || blue != maskBlue )
347 {
348 if ( alpha > 0 )
349 {
350 avgRed += red ;
351 avgGreen += green ;
352 avgBlue += blue ;
353 }
354 avgAlpha += alpha ;
355 counter++ ;
356 }
357 }
358 }
359 if ( counter == 0 )
360 {
361 *(target_data++) = M_IMGDATA->m_maskRed ;
362 *(target_data++) = M_IMGDATA->m_maskGreen ;
363 *(target_data++) = M_IMGDATA->m_maskBlue ;
364 }
365 else
366 {
367 if ( source_alpha )
368 *(target_alpha++) = (unsigned char)(avgAlpha / counter ) ;
369 *(target_data++) = (unsigned char)(avgRed / counter);
370 *(target_data++) = (unsigned char)(avgGreen / counter);
371 *(target_data++) = (unsigned char)(avgBlue / counter);
372 }
373 }
374 }
375
376 // In case this is a cursor, make sure the hotspot is scaled accordingly:
377 if ( HasOption(wxIMAGE_OPTION_CUR_HOTSPOT_X) )
378 image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X,
379 (GetOptionInt(wxIMAGE_OPTION_CUR_HOTSPOT_X))/xFactor);
380 if ( HasOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y) )
381 image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y,
382 (GetOptionInt(wxIMAGE_OPTION_CUR_HOTSPOT_Y))/yFactor);
383
384 return image;
385 }
386
387 wxImage
388 wxImage::Scale( int width, int height, wxImageResizeQuality quality ) const
389 {
390 wxImage image;
391
392 wxCHECK_MSG( Ok(), image, wxT("invalid image") );
393
394 // can't scale to/from 0 size
395 wxCHECK_MSG( (width > 0) && (height > 0), image,
396 wxT("invalid new image size") );
397
398 long old_height = M_IMGDATA->m_height,
399 old_width = M_IMGDATA->m_width;
400 wxCHECK_MSG( (old_height > 0) && (old_width > 0), image,
401 wxT("invalid old image size") );
402
403 // If the image's new width and height are the same as the original, no
404 // need to waste time or CPU cycles
405 if ( old_width == width && old_height == height )
406 return *this;
407
408 // resample the image using either the nearest neighbourhood, bilinear or
409 // bicubic method as specified
410 switch ( quality )
411 {
412 case wxIMAGE_QUALITY_BICUBIC:
413 case wxIMAGE_QUALITY_BILINEAR:
414 // both of these algorithms should be used for up-sampling the
415 // image only, when down-sampling always use box averaging for best
416 // results
417 if ( width < old_width && height < old_height )
418 image = ResampleBox(width, height);
419 else if ( quality == wxIMAGE_QUALITY_BILINEAR )
420 image = ResampleBilinear(width, height);
421 else if ( quality == wxIMAGE_QUALITY_BICUBIC )
422 image = ResampleBicubic(width, height);
423 break;
424
425 case wxIMAGE_QUALITY_NEAREST:
426 if ( old_width % width == 0 && old_width >= width &&
427 old_height % height == 0 && old_height >= height )
428 {
429 return ShrinkBy( old_width / width , old_height / height );
430 }
431
432 image = ResampleNearest(width, height);
433 break;
434 }
435
436 // If the original image has a mask, apply the mask to the new image
437 if (M_IMGDATA->m_hasMask)
438 {
439 image.SetMaskColour( M_IMGDATA->m_maskRed,
440 M_IMGDATA->m_maskGreen,
441 M_IMGDATA->m_maskBlue );
442 }
443
444 // In case this is a cursor, make sure the hotspot is scaled accordingly:
445 if ( HasOption(wxIMAGE_OPTION_CUR_HOTSPOT_X) )
446 image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X,
447 (GetOptionInt(wxIMAGE_OPTION_CUR_HOTSPOT_X)*width)/old_width);
448 if ( HasOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y) )
449 image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y,
450 (GetOptionInt(wxIMAGE_OPTION_CUR_HOTSPOT_Y)*height)/old_height);
451
452 return image;
453 }
454
455 wxImage wxImage::ResampleNearest(int width, int height) const
456 {
457 wxImage image;
458 image.Create( width, height, false );
459
460 unsigned char *data = image.GetData();
461
462 wxCHECK_MSG( data, image, wxT("unable to create image") );
463
464 unsigned char *source_data = M_IMGDATA->m_data;
465 unsigned char *target_data = data;
466 unsigned char *source_alpha = 0 ;
467 unsigned char *target_alpha = 0 ;
468
469 if ( !M_IMGDATA->m_hasMask )
470 {
471 source_alpha = M_IMGDATA->m_alpha ;
472 if ( source_alpha )
473 {
474 image.SetAlpha() ;
475 target_alpha = image.GetAlpha() ;
476 }
477 }
478
479 long old_height = M_IMGDATA->m_height,
480 old_width = M_IMGDATA->m_width;
481 long x_delta = (old_width<<16) / width;
482 long y_delta = (old_height<<16) / height;
483
484 unsigned char* dest_pixel = target_data;
485
486 long y = 0;
487 for ( long j = 0; j < height; j++ )
488 {
489 unsigned char* src_line = &source_data[(y>>16)*old_width*3];
490 unsigned char* src_alpha_line = source_alpha ? &source_alpha[(y>>16)*old_width] : 0 ;
491
492 long x = 0;
493 for ( long i = 0; i < width; i++ )
494 {
495 unsigned char* src_pixel = &src_line[(x>>16)*3];
496 unsigned char* src_alpha_pixel = source_alpha ? &src_alpha_line[(x>>16)] : 0 ;
497 dest_pixel[0] = src_pixel[0];
498 dest_pixel[1] = src_pixel[1];
499 dest_pixel[2] = src_pixel[2];
500 dest_pixel += 3;
501 if ( source_alpha )
502 *(target_alpha++) = *src_alpha_pixel ;
503 x += x_delta;
504 }
505
506 y += y_delta;
507 }
508
509 return image;
510 }
511
512 wxImage wxImage::ResampleBox(int width, int height) const
513 {
514 // This function implements a simple pre-blur/box averaging method for
515 // downsampling that gives reasonably smooth results To scale the image
516 // down we will need to gather a grid of pixels of the size of the scale
517 // factor in each direction and then do an averaging of the pixels.
518
519 wxImage ret_image(width, height, false);
520
521 const double scale_factor_x = double(M_IMGDATA->m_width) / width;
522 const double scale_factor_y = double(M_IMGDATA->m_height) / height;
523
524 const int scale_factor_x_2 = (int)(scale_factor_x / 2);
525 const int scale_factor_y_2 = (int)(scale_factor_y / 2);
526
527 unsigned char* src_data = M_IMGDATA->m_data;
528 unsigned char* src_alpha = M_IMGDATA->m_alpha;
529 unsigned char* dst_data = ret_image.GetData();
530 unsigned char* dst_alpha = NULL;
531
532 if ( src_alpha )
533 {
534 ret_image.SetAlpha();
535 dst_alpha = ret_image.GetAlpha();
536 }
537
538 int averaged_pixels, src_pixel_index;
539 double sum_r, sum_g, sum_b, sum_a;
540
541 for ( int y = 0; y < height; y++ ) // Destination image - Y direction
542 {
543 // Source pixel in the Y direction
544 int src_y = (int)(y * scale_factor_y);
545
546 for ( int x = 0; x < width; x++ ) // Destination image - X direction
547 {
548 // Source pixel in the X direction
549 int src_x = (int)(x * scale_factor_x);
550
551 // Box of pixels to average
552 averaged_pixels = 0;
553 sum_r = sum_g = sum_b = sum_a = 0.0;
554
555 for ( int j = int(src_y - scale_factor_y/2.0 + 1);
556 j <= int(src_y + scale_factor_y_2);
557 j++ )
558 {
559 // We don't care to average pixels that don't exist (edges)
560 if ( j < 0 || j > M_IMGDATA->m_height - 1 )
561 continue;
562
563 for ( int i = int(src_x - scale_factor_x/2.0 + 1);
564 i <= src_x + scale_factor_x_2;
565 i++ )
566 {
567 // Don't average edge pixels
568 if ( i < 0 || i > M_IMGDATA->m_width - 1 )
569 continue;
570
571 // Calculate the actual index in our source pixels
572 src_pixel_index = j * M_IMGDATA->m_width + i;
573
574 sum_r += src_data[src_pixel_index * 3 + 0];
575 sum_g += src_data[src_pixel_index * 3 + 1];
576 sum_b += src_data[src_pixel_index * 3 + 2];
577 if ( src_alpha )
578 sum_a += src_alpha[src_pixel_index];
579
580 averaged_pixels++;
581 }
582 }
583
584 // Calculate the average from the sum and number of averaged pixels
585 dst_data[0] = (unsigned char)(sum_r / averaged_pixels);
586 dst_data[1] = (unsigned char)(sum_g / averaged_pixels);
587 dst_data[2] = (unsigned char)(sum_b / averaged_pixels);
588 dst_data += 3;
589 if ( src_alpha )
590 *dst_alpha++ = (unsigned char)(sum_a / averaged_pixels);
591 }
592 }
593
594 return ret_image;
595 }
596
597 wxImage wxImage::ResampleBilinear(int width, int height) const
598 {
599 // This function implements a Bilinear algorithm for resampling.
600 wxImage ret_image(width, height, false);
601 unsigned char* src_data = M_IMGDATA->m_data;
602 unsigned char* src_alpha = M_IMGDATA->m_alpha;
603 unsigned char* dst_data = ret_image.GetData();
604 unsigned char* dst_alpha = NULL;
605
606 if ( src_alpha )
607 {
608 ret_image.SetAlpha();
609 dst_alpha = ret_image.GetAlpha();
610 }
611 double HFactor = double(M_IMGDATA->m_height) / height;
612 double WFactor = double(M_IMGDATA->m_width) / width;
613
614 int srcpixymax = M_IMGDATA->m_height - 1;
615 int srcpixxmax = M_IMGDATA->m_width - 1;
616
617 double srcpixy, srcpixy1, srcpixy2, dy, dy1;
618 double srcpixx, srcpixx1, srcpixx2, dx, dx1;
619 double r1, g1, b1, a1;
620 double r2, g2, b2, a2;
621
622 for ( int dsty = 0; dsty < height; dsty++ )
623 {
624 // We need to calculate the source pixel to interpolate from - Y-axis
625 srcpixy = double(dsty) * HFactor;
626 srcpixy1 = int(srcpixy);
627 srcpixy2 = ( srcpixy1 == srcpixymax ) ? srcpixy1 : srcpixy1 + 1.0;
628 dy = srcpixy - (int)srcpixy;
629 dy1 = 1.0 - dy;
630
631
632 for ( int dstx = 0; dstx < width; dstx++ )
633 {
634 // X-axis of pixel to interpolate from
635 srcpixx = double(dstx) * WFactor;
636 srcpixx1 = int(srcpixx);
637 srcpixx2 = ( srcpixx1 == srcpixxmax ) ? srcpixx1 : srcpixx1 + 1.0;
638 dx = srcpixx - (int)srcpixx;
639 dx1 = 1.0 - dx;
640
641 int x_offset1 = srcpixx1 < 0.0 ? 0 : srcpixx1 > srcpixxmax ? srcpixxmax : (int)srcpixx1;
642 int x_offset2 = srcpixx2 < 0.0 ? 0 : srcpixx2 > srcpixxmax ? srcpixxmax : (int)srcpixx2;
643 int y_offset1 = srcpixy1 < 0.0 ? 0 : srcpixy1 > srcpixymax ? srcpixymax : (int)srcpixy1;
644 int y_offset2 = srcpixy2 < 0.0 ? 0 : srcpixy2 > srcpixymax ? srcpixymax : (int)srcpixy2;
645
646 int src_pixel_index00 = y_offset1 * M_IMGDATA->m_width + x_offset1;
647 int src_pixel_index01 = y_offset1 * M_IMGDATA->m_width + x_offset2;
648 int src_pixel_index10 = y_offset2 * M_IMGDATA->m_width + x_offset1;
649 int src_pixel_index11 = y_offset2 * M_IMGDATA->m_width + x_offset2;
650
651 //first line
652 r1 = src_data[src_pixel_index00 * 3 + 0] * dx1 + src_data[src_pixel_index01 * 3 + 0] * dx;
653 g1 = src_data[src_pixel_index00 * 3 + 1] * dx1 + src_data[src_pixel_index01 * 3 + 1] * dx;
654 b1 = src_data[src_pixel_index00 * 3 + 2] * dx1 + src_data[src_pixel_index01 * 3 + 2] * dx;
655 if ( src_alpha )
656 a1 = src_alpha[src_pixel_index00] * dx1 + src_alpha[src_pixel_index01] * dx;
657
658 //second line
659 r2 = src_data[src_pixel_index10 * 3 + 0] * dx1 + src_data[src_pixel_index11 * 3 + 0] * dx;
660 g2 = src_data[src_pixel_index10 * 3 + 1] * dx1 + src_data[src_pixel_index11 * 3 + 1] * dx;
661 b2 = src_data[src_pixel_index10 * 3 + 2] * dx1 + src_data[src_pixel_index11 * 3 + 2] * dx;
662 if ( src_alpha )
663 a2 = src_alpha[src_pixel_index10] * dx1 + src_alpha[src_pixel_index11] * dx;
664
665 //result lines
666
667 dst_data[0] = r1 * dy1 + r2 * dy;
668 dst_data[1] = g1 * dy1 + g2 * dy;
669 dst_data[2] = b1 * dy1 + b2 * dy;
670 dst_data += 3;
671
672 if ( src_alpha )
673 *dst_alpha++ = a1 * dy1 + a2 * dy;
674 }
675 }
676
677 return ret_image;
678 }
679
680 // The following two local functions are for the B-spline weighting of the
681 // bicubic sampling algorithm
682 static inline double spline_cube(double value)
683 {
684 return value <= 0.0 ? 0.0 : value * value * value;
685 }
686
687 static inline double spline_weight(double value)
688 {
689 return (spline_cube(value + 2) -
690 4 * spline_cube(value + 1) +
691 6 * spline_cube(value) -
692 4 * spline_cube(value - 1)) / 6;
693 }
694
695 // This is the bicubic resampling algorithm
696 wxImage wxImage::ResampleBicubic(int width, int height) const
697 {
698 // This function implements a Bicubic B-Spline algorithm for resampling.
699 // This method is certainly a little slower than wxImage's default pixel
700 // replication method, however for most reasonably sized images not being
701 // upsampled too much on a fairly average CPU this difference is hardly
702 // noticeable and the results are far more pleasing to look at.
703 //
704 // This particular bicubic algorithm does pixel weighting according to a
705 // B-Spline that basically implements a Gaussian bell-like weighting
706 // kernel. Because of this method the results may appear a bit blurry when
707 // upsampling by large factors. This is basically because a slight
708 // gaussian blur is being performed to get the smooth look of the upsampled
709 // image.
710
711 // Edge pixels: 3-4 possible solutions
712 // - (Wrap/tile) Wrap the image, take the color value from the opposite
713 // side of the image.
714 // - (Mirror) Duplicate edge pixels, so that pixel at coordinate (2, n),
715 // where n is nonpositive, will have the value of (2, 1).
716 // - (Ignore) Simply ignore the edge pixels and apply the kernel only to
717 // pixels which do have all neighbours.
718 // - (Clamp) Choose the nearest pixel along the border. This takes the
719 // border pixels and extends them out to infinity.
720 //
721 // NOTE: below the y_offset and x_offset variables are being set for edge
722 // pixels using the "Mirror" method mentioned above
723
724 wxImage ret_image;
725
726 ret_image.Create(width, height, false);
727
728 unsigned char* src_data = M_IMGDATA->m_data;
729 unsigned char* src_alpha = M_IMGDATA->m_alpha;
730 unsigned char* dst_data = ret_image.GetData();
731 unsigned char* dst_alpha = NULL;
732
733 if ( src_alpha )
734 {
735 ret_image.SetAlpha();
736 dst_alpha = ret_image.GetAlpha();
737 }
738
739 for ( int dsty = 0; dsty < height; dsty++ )
740 {
741 // We need to calculate the source pixel to interpolate from - Y-axis
742 double srcpixy = double(dsty * M_IMGDATA->m_height) / height;
743 double dy = srcpixy - (int)srcpixy;
744
745 for ( int dstx = 0; dstx < width; dstx++ )
746 {
747 // X-axis of pixel to interpolate from
748 double srcpixx = double(dstx * M_IMGDATA->m_width) / width;
749 double dx = srcpixx - (int)srcpixx;
750
751 // Sums for each color channel
752 double sum_r = 0, sum_g = 0, sum_b = 0, sum_a = 0;
753
754 // Here we actually determine the RGBA values for the destination pixel
755 for ( int k = -1; k <= 2; k++ )
756 {
757 // Y offset
758 int y_offset = srcpixy + k < 0.0
759 ? 0
760 : srcpixy + k >= M_IMGDATA->m_height
761 ? M_IMGDATA->m_height - 1
762 : (int)(srcpixy + k);
763
764 // Loop across the X axis
765 for ( int i = -1; i <= 2; i++ )
766 {
767 // X offset
768 int x_offset = srcpixx + i < 0.0
769 ? 0
770 : srcpixx + i >= M_IMGDATA->m_width
771 ? M_IMGDATA->m_width - 1
772 : (int)(srcpixx + i);
773
774 // Calculate the exact position where the source data
775 // should be pulled from based on the x_offset and y_offset
776 int src_pixel_index = y_offset*M_IMGDATA->m_width + x_offset;
777
778 // Calculate the weight for the specified pixel according
779 // to the bicubic b-spline kernel we're using for
780 // interpolation
781 double
782 pixel_weight = spline_weight(i - dx)*spline_weight(k - dy);
783
784 // Create a sum of all velues for each color channel
785 // adjusted for the pixel's calculated weight
786 sum_r += src_data[src_pixel_index * 3 + 0] * pixel_weight;
787 sum_g += src_data[src_pixel_index * 3 + 1] * pixel_weight;
788 sum_b += src_data[src_pixel_index * 3 + 2] * pixel_weight;
789 if ( src_alpha )
790 sum_a += src_alpha[src_pixel_index] * pixel_weight;
791 }
792 }
793
794 // Put the data into the destination image. The summed values are
795 // of double data type and are rounded here for accuracy
796 dst_data[0] = (unsigned char)(sum_r + 0.5);
797 dst_data[1] = (unsigned char)(sum_g + 0.5);
798 dst_data[2] = (unsigned char)(sum_b + 0.5);
799 dst_data += 3;
800
801 if ( src_alpha )
802 *dst_alpha++ = (unsigned char)sum_a;
803 }
804 }
805
806 return ret_image;
807 }
808
809 // Blur in the horizontal direction
810 wxImage wxImage::BlurHorizontal(int blurRadius) const
811 {
812 wxImage ret_image;
813 ret_image.Create(M_IMGDATA->m_width, M_IMGDATA->m_height, false);
814
815 unsigned char* src_data = M_IMGDATA->m_data;
816 unsigned char* dst_data = ret_image.GetData();
817 unsigned char* src_alpha = M_IMGDATA->m_alpha;
818 unsigned char* dst_alpha = NULL;
819
820 // Check for a mask or alpha
821 if ( src_alpha )
822 {
823 ret_image.SetAlpha();
824 dst_alpha = ret_image.GetAlpha();
825 }
826 else if ( M_IMGDATA->m_hasMask )
827 {
828 ret_image.SetMaskColour(M_IMGDATA->m_maskRed,
829 M_IMGDATA->m_maskGreen,
830 M_IMGDATA->m_maskBlue);
831 }
832
833 // number of pixels we average over
834 const int blurArea = blurRadius*2 + 1;
835
836 // Horizontal blurring algorithm - average all pixels in the specified blur
837 // radius in the X or horizontal direction
838 for ( int y = 0; y < M_IMGDATA->m_height; y++ )
839 {
840 // Variables used in the blurring algorithm
841 long sum_r = 0,
842 sum_g = 0,
843 sum_b = 0,
844 sum_a = 0;
845
846 long pixel_idx;
847 const unsigned char *src;
848 unsigned char *dst;
849
850 // Calculate the average of all pixels in the blur radius for the first
851 // pixel of the row
852 for ( int kernel_x = -blurRadius; kernel_x <= blurRadius; kernel_x++ )
853 {
854 // To deal with the pixels at the start of a row so it's not
855 // grabbing GOK values from memory at negative indices of the
856 // image's data or grabbing from the previous row
857 if ( kernel_x < 0 )
858 pixel_idx = y * M_IMGDATA->m_width;
859 else
860 pixel_idx = kernel_x + y * M_IMGDATA->m_width;
861
862 src = src_data + pixel_idx*3;
863 sum_r += src[0];
864 sum_g += src[1];
865 sum_b += src[2];
866 if ( src_alpha )
867 sum_a += src_alpha[pixel_idx];
868 }
869
870 dst = dst_data + y * M_IMGDATA->m_width*3;
871 dst[0] = (unsigned char)(sum_r / blurArea);
872 dst[1] = (unsigned char)(sum_g / blurArea);
873 dst[2] = (unsigned char)(sum_b / blurArea);
874 if ( src_alpha )
875 dst_alpha[y * M_IMGDATA->m_width] = (unsigned char)(sum_a / blurArea);
876
877 // Now average the values of the rest of the pixels by just moving the
878 // blur radius box along the row
879 for ( int x = 1; x < M_IMGDATA->m_width; x++ )
880 {
881 // Take care of edge pixels on the left edge by essentially
882 // duplicating the edge pixel
883 if ( x - blurRadius - 1 < 0 )
884 pixel_idx = y * M_IMGDATA->m_width;
885 else
886 pixel_idx = (x - blurRadius - 1) + y * M_IMGDATA->m_width;
887
888 // Subtract the value of the pixel at the left side of the blur
889 // radius box
890 src = src_data + pixel_idx*3;
891 sum_r -= src[0];
892 sum_g -= src[1];
893 sum_b -= src[2];
894 if ( src_alpha )
895 sum_a -= src_alpha[pixel_idx];
896
897 // Take care of edge pixels on the right edge
898 if ( x + blurRadius > M_IMGDATA->m_width - 1 )
899 pixel_idx = M_IMGDATA->m_width - 1 + y * M_IMGDATA->m_width;
900 else
901 pixel_idx = x + blurRadius + y * M_IMGDATA->m_width;
902
903 // Add the value of the pixel being added to the end of our box
904 src = src_data + pixel_idx*3;
905 sum_r += src[0];
906 sum_g += src[1];
907 sum_b += src[2];
908 if ( src_alpha )
909 sum_a += src_alpha[pixel_idx];
910
911 // Save off the averaged data
912 dst = dst_data + x*3 + y*M_IMGDATA->m_width*3;
913 dst[0] = (unsigned char)(sum_r / blurArea);
914 dst[1] = (unsigned char)(sum_g / blurArea);
915 dst[2] = (unsigned char)(sum_b / blurArea);
916 if ( src_alpha )
917 dst_alpha[x + y * M_IMGDATA->m_width] = (unsigned char)(sum_a / blurArea);
918 }
919 }
920
921 return ret_image;
922 }
923
924 // Blur in the vertical direction
925 wxImage wxImage::BlurVertical(int blurRadius) const
926 {
927 wxImage ret_image;
928 ret_image.Create(M_IMGDATA->m_width, M_IMGDATA->m_height, false);
929
930 unsigned char* src_data = M_IMGDATA->m_data;
931 unsigned char* dst_data = ret_image.GetData();
932 unsigned char* src_alpha = M_IMGDATA->m_alpha;
933 unsigned char* dst_alpha = NULL;
934
935 // Check for a mask or alpha
936 if ( src_alpha )
937 {
938 ret_image.SetAlpha();
939 dst_alpha = ret_image.GetAlpha();
940 }
941 else if ( M_IMGDATA->m_hasMask )
942 {
943 ret_image.SetMaskColour(M_IMGDATA->m_maskRed,
944 M_IMGDATA->m_maskGreen,
945 M_IMGDATA->m_maskBlue);
946 }
947
948 // number of pixels we average over
949 const int blurArea = blurRadius*2 + 1;
950
951 // Vertical blurring algorithm - same as horizontal but switched the
952 // opposite direction
953 for ( int x = 0; x < M_IMGDATA->m_width; x++ )
954 {
955 // Variables used in the blurring algorithm
956 long sum_r = 0,
957 sum_g = 0,
958 sum_b = 0,
959 sum_a = 0;
960
961 long pixel_idx;
962 const unsigned char *src;
963 unsigned char *dst;
964
965 // Calculate the average of all pixels in our blur radius box for the
966 // first pixel of the column
967 for ( int kernel_y = -blurRadius; kernel_y <= blurRadius; kernel_y++ )
968 {
969 // To deal with the pixels at the start of a column so it's not
970 // grabbing GOK values from memory at negative indices of the
971 // image's data or grabbing from the previous column
972 if ( kernel_y < 0 )
973 pixel_idx = x;
974 else
975 pixel_idx = x + kernel_y * M_IMGDATA->m_width;
976
977 src = src_data + pixel_idx*3;
978 sum_r += src[0];
979 sum_g += src[1];
980 sum_b += src[2];
981 if ( src_alpha )
982 sum_a += src_alpha[pixel_idx];
983 }
984
985 dst = dst_data + x*3;
986 dst[0] = (unsigned char)(sum_r / blurArea);
987 dst[1] = (unsigned char)(sum_g / blurArea);
988 dst[2] = (unsigned char)(sum_b / blurArea);
989 if ( src_alpha )
990 dst_alpha[x] = (unsigned char)(sum_a / blurArea);
991
992 // Now average the values of the rest of the pixels by just moving the
993 // box along the column from top to bottom
994 for ( int y = 1; y < M_IMGDATA->m_height; y++ )
995 {
996 // Take care of pixels that would be beyond the top edge by
997 // duplicating the top edge pixel for the column
998 if ( y - blurRadius - 1 < 0 )
999 pixel_idx = x;
1000 else
1001 pixel_idx = x + (y - blurRadius - 1) * M_IMGDATA->m_width;
1002
1003 // Subtract the value of the pixel at the top of our blur radius box
1004 src = src_data + pixel_idx*3;
1005 sum_r -= src[0];
1006 sum_g -= src[1];
1007 sum_b -= src[2];
1008 if ( src_alpha )
1009 sum_a -= src_alpha[pixel_idx];
1010
1011 // Take care of the pixels that would be beyond the bottom edge of
1012 // the image similar to the top edge
1013 if ( y + blurRadius > M_IMGDATA->m_height - 1 )
1014 pixel_idx = x + (M_IMGDATA->m_height - 1) * M_IMGDATA->m_width;
1015 else
1016 pixel_idx = x + (blurRadius + y) * M_IMGDATA->m_width;
1017
1018 // Add the value of the pixel being added to the end of our box
1019 src = src_data + pixel_idx*3;
1020 sum_r += src[0];
1021 sum_g += src[1];
1022 sum_b += src[2];
1023 if ( src_alpha )
1024 sum_a += src_alpha[pixel_idx];
1025
1026 // Save off the averaged data
1027 dst = dst_data + (x + y * M_IMGDATA->m_width) * 3;
1028 dst[0] = (unsigned char)(sum_r / blurArea);
1029 dst[1] = (unsigned char)(sum_g / blurArea);
1030 dst[2] = (unsigned char)(sum_b / blurArea);
1031 if ( src_alpha )
1032 dst_alpha[x + y * M_IMGDATA->m_width] = (unsigned char)(sum_a / blurArea);
1033 }
1034 }
1035
1036 return ret_image;
1037 }
1038
1039 // The new blur function
1040 wxImage wxImage::Blur(int blurRadius) const
1041 {
1042 wxImage ret_image;
1043 ret_image.Create(M_IMGDATA->m_width, M_IMGDATA->m_height, false);
1044
1045 // Blur the image in each direction
1046 ret_image = BlurHorizontal(blurRadius);
1047 ret_image = ret_image.BlurVertical(blurRadius);
1048
1049 return ret_image;
1050 }
1051
1052 wxImage wxImage::Rotate90( bool clockwise ) const
1053 {
1054 wxImage image;
1055
1056 wxCHECK_MSG( Ok(), image, wxT("invalid image") );
1057
1058 image.Create( M_IMGDATA->m_height, M_IMGDATA->m_width, false );
1059
1060 unsigned char *data = image.GetData();
1061
1062 wxCHECK_MSG( data, image, wxT("unable to create image") );
1063
1064 unsigned char *source_data = M_IMGDATA->m_data;
1065 unsigned char *target_data;
1066 unsigned char *alpha_data = 0 ;
1067 unsigned char *source_alpha = 0 ;
1068 unsigned char *target_alpha = 0 ;
1069
1070 if (M_IMGDATA->m_hasMask)
1071 {
1072 image.SetMaskColour( M_IMGDATA->m_maskRed, M_IMGDATA->m_maskGreen, M_IMGDATA->m_maskBlue );
1073 }
1074 else
1075 {
1076 source_alpha = M_IMGDATA->m_alpha ;
1077 if ( source_alpha )
1078 {
1079 image.SetAlpha() ;
1080 alpha_data = image.GetAlpha() ;
1081 }
1082 }
1083
1084 long height = M_IMGDATA->m_height;
1085 long width = M_IMGDATA->m_width;
1086
1087 for (long j = 0; j < height; j++)
1088 {
1089 for (long i = 0; i < width; i++)
1090 {
1091 if (clockwise)
1092 {
1093 target_data = data + (((i+1)*height) - j - 1)*3;
1094 if(source_alpha)
1095 target_alpha = alpha_data + (((i+1)*height) - j - 1);
1096 }
1097 else
1098 {
1099 target_data = data + ((height*(width-1)) + j - (i*height))*3;
1100 if(source_alpha)
1101 target_alpha = alpha_data + ((height*(width-1)) + j - (i*height));
1102 }
1103 memcpy( target_data, source_data, 3 );
1104 source_data += 3;
1105
1106 if(source_alpha)
1107 {
1108 memcpy( target_alpha, source_alpha, 1 );
1109 source_alpha += 1;
1110 }
1111 }
1112 }
1113
1114 return image;
1115 }
1116
1117 wxImage wxImage::Mirror( bool horizontally ) const
1118 {
1119 wxImage image;
1120
1121 wxCHECK_MSG( Ok(), image, wxT("invalid image") );
1122
1123 image.Create( M_IMGDATA->m_width, M_IMGDATA->m_height, false );
1124
1125 unsigned char *data = image.GetData();
1126 unsigned char *alpha = NULL;
1127
1128 wxCHECK_MSG( data, image, wxT("unable to create image") );
1129
1130 if (M_IMGDATA->m_alpha != NULL) {
1131 image.SetAlpha();
1132 alpha = image.GetAlpha();
1133 wxCHECK_MSG( alpha, image, wxT("unable to create alpha channel") );
1134 }
1135
1136 if (M_IMGDATA->m_hasMask)
1137 image.SetMaskColour( M_IMGDATA->m_maskRed, M_IMGDATA->m_maskGreen, M_IMGDATA->m_maskBlue );
1138
1139 long height = M_IMGDATA->m_height;
1140 long width = M_IMGDATA->m_width;
1141
1142 unsigned char *source_data = M_IMGDATA->m_data;
1143 unsigned char *target_data;
1144
1145 if (horizontally)
1146 {
1147 for (long j = 0; j < height; j++)
1148 {
1149 data += width*3;
1150 target_data = data-3;
1151 for (long i = 0; i < width; i++)
1152 {
1153 memcpy( target_data, source_data, 3 );
1154 source_data += 3;
1155 target_data -= 3;
1156 }
1157 }
1158
1159 if (alpha != NULL)
1160 {
1161 // src_alpha starts at the first pixel and increases by 1 after each step
1162 // (a step here is the copy of the alpha value of one pixel)
1163 const unsigned char *src_alpha = M_IMGDATA->m_alpha;
1164 // dest_alpha starts just beyond the first line, decreases before each step,
1165 // and after each line is finished, increases by 2 widths (skipping the line
1166 // just copied and the line that will be copied next)
1167 unsigned char *dest_alpha = alpha + width;
1168
1169 for (long jj = 0; jj < height; ++jj)
1170 {
1171 for (long i = 0; i < width; ++i) {
1172 *(--dest_alpha) = *(src_alpha++); // copy one pixel
1173 }
1174 dest_alpha += 2 * width; // advance beyond the end of the next line
1175 }
1176 }
1177 }
1178 else
1179 {
1180 for (long i = 0; i < height; i++)
1181 {
1182 target_data = data + 3*width*(height-1-i);
1183 memcpy( target_data, source_data, (size_t)3*width );
1184 source_data += 3*width;
1185 }
1186
1187 if (alpha != NULL)
1188 {
1189 // src_alpha starts at the first pixel and increases by 1 width after each step
1190 // (a step here is the copy of the alpha channel of an entire line)
1191 const unsigned char *src_alpha = M_IMGDATA->m_alpha;
1192 // dest_alpha starts just beyond the last line (beyond the whole image)
1193 // and decreases by 1 width before each step
1194 unsigned char *dest_alpha = alpha + width * height;
1195
1196 for (long jj = 0; jj < height; ++jj)
1197 {
1198 dest_alpha -= width;
1199 memcpy( dest_alpha, src_alpha, (size_t)width );
1200 src_alpha += width;
1201 }
1202 }
1203 }
1204
1205 return image;
1206 }
1207
1208 wxImage wxImage::GetSubImage( const wxRect &rect ) const
1209 {
1210 wxImage image;
1211
1212 wxCHECK_MSG( Ok(), image, wxT("invalid image") );
1213
1214 wxCHECK_MSG( (rect.GetLeft()>=0) && (rect.GetTop()>=0) &&
1215 (rect.GetRight()<=GetWidth()) && (rect.GetBottom()<=GetHeight()),
1216 image, wxT("invalid subimage size") );
1217
1218 const int subwidth = rect.GetWidth();
1219 const int subheight = rect.GetHeight();
1220
1221 image.Create( subwidth, subheight, false );
1222
1223 const unsigned char *src_data = GetData();
1224 const unsigned char *src_alpha = M_IMGDATA->m_alpha;
1225 unsigned char *subdata = image.GetData();
1226 unsigned char *subalpha = NULL;
1227
1228 wxCHECK_MSG( subdata, image, wxT("unable to create image") );
1229
1230 if (src_alpha != NULL) {
1231 image.SetAlpha();
1232 subalpha = image.GetAlpha();
1233 wxCHECK_MSG( subalpha, image, wxT("unable to create alpha channel"));
1234 }
1235
1236 if (M_IMGDATA->m_hasMask)
1237 image.SetMaskColour( M_IMGDATA->m_maskRed, M_IMGDATA->m_maskGreen, M_IMGDATA->m_maskBlue );
1238
1239 const int width = GetWidth();
1240 const int pixsoff = rect.GetLeft() + width * rect.GetTop();
1241
1242 src_data += 3 * pixsoff;
1243 src_alpha += pixsoff; // won't be used if was NULL, so this is ok
1244
1245 for (long j = 0; j < subheight; ++j)
1246 {
1247 memcpy( subdata, src_data, 3 * subwidth );
1248 subdata += 3 * subwidth;
1249 src_data += 3 * width;
1250 if (subalpha != NULL) {
1251 memcpy( subalpha, src_alpha, subwidth );
1252 subalpha += subwidth;
1253 src_alpha += width;
1254 }
1255 }
1256
1257 return image;
1258 }
1259
1260 wxImage wxImage::Size( const wxSize& size, const wxPoint& pos,
1261 int r_, int g_, int b_ ) const
1262 {
1263 wxImage image;
1264
1265 wxCHECK_MSG( Ok(), image, wxT("invalid image") );
1266 wxCHECK_MSG( (size.GetWidth() > 0) && (size.GetHeight() > 0), image, wxT("invalid size") );
1267
1268 int width = GetWidth(), height = GetHeight();
1269 image.Create(size.GetWidth(), size.GetHeight(), false);
1270
1271 unsigned char r = (unsigned char)r_;
1272 unsigned char g = (unsigned char)g_;
1273 unsigned char b = (unsigned char)b_;
1274 if ((r_ == -1) && (g_ == -1) && (b_ == -1))
1275 {
1276 GetOrFindMaskColour( &r, &g, &b );
1277 image.SetMaskColour(r, g, b);
1278 }
1279
1280 image.SetRGB(wxRect(), r, g, b);
1281
1282 // we have two coordinate systems:
1283 // source: starting at 0,0 of source image
1284 // destination starting at 0,0 of destination image
1285 // Documentation says:
1286 // "The image is pasted into a new image [...] at the position pos relative
1287 // to the upper left of the new image." this means the transition rule is:
1288 // "dest coord" = "source coord" + pos;
1289
1290 // calculate the intersection using source coordinates:
1291 wxRect srcRect(0, 0, width, height);
1292 wxRect dstRect(-pos, size);
1293
1294 srcRect.Intersect(dstRect);
1295
1296 if (!srcRect.IsEmpty())
1297 {
1298 // insertion point is needed in destination coordinates.
1299 // NB: it is not always "pos"!
1300 wxPoint ptInsert = srcRect.GetTopLeft() + pos;
1301
1302 if ((srcRect.GetWidth() == width) && (srcRect.GetHeight() == height))
1303 image.Paste(*this, ptInsert.x, ptInsert.y);
1304 else
1305 image.Paste(GetSubImage(srcRect), ptInsert.x, ptInsert.y);
1306 }
1307
1308 return image;
1309 }
1310
1311 void wxImage::Paste( const wxImage &image, int x, int y )
1312 {
1313 wxCHECK_RET( Ok(), wxT("invalid image") );
1314 wxCHECK_RET( image.Ok(), wxT("invalid image") );
1315
1316 AllocExclusive();
1317
1318 int xx = 0;
1319 int yy = 0;
1320 int width = image.GetWidth();
1321 int height = image.GetHeight();
1322
1323 if (x < 0)
1324 {
1325 xx = -x;
1326 width += x;
1327 }
1328 if (y < 0)
1329 {
1330 yy = -y;
1331 height += y;
1332 }
1333
1334 if ((x+xx)+width > M_IMGDATA->m_width)
1335 width = M_IMGDATA->m_width - (x+xx);
1336 if ((y+yy)+height > M_IMGDATA->m_height)
1337 height = M_IMGDATA->m_height - (y+yy);
1338
1339 if (width < 1) return;
1340 if (height < 1) return;
1341
1342 if ((!HasMask() && !image.HasMask()) ||
1343 (HasMask() && !image.HasMask()) ||
1344 ((HasMask() && image.HasMask() &&
1345 (GetMaskRed()==image.GetMaskRed()) &&
1346 (GetMaskGreen()==image.GetMaskGreen()) &&
1347 (GetMaskBlue()==image.GetMaskBlue()))))
1348 {
1349 unsigned char* source_data = image.GetData() + xx*3 + yy*3*image.GetWidth();
1350 int source_step = image.GetWidth()*3;
1351
1352 unsigned char* target_data = GetData() + (x+xx)*3 + (y+yy)*3*M_IMGDATA->m_width;
1353 int target_step = M_IMGDATA->m_width*3;
1354 for (int j = 0; j < height; j++)
1355 {
1356 memcpy( target_data, source_data, width*3 );
1357 source_data += source_step;
1358 target_data += target_step;
1359 }
1360 }
1361
1362 // Copy over the alpha channel from the original image
1363 if ( image.HasAlpha() )
1364 {
1365 if ( !HasAlpha() )
1366 InitAlpha();
1367
1368 unsigned char* source_data = image.GetAlpha() + xx + yy*image.GetWidth();
1369 int source_step = image.GetWidth();
1370
1371 unsigned char* target_data = GetAlpha() + (x+xx) + (y+yy)*M_IMGDATA->m_width;
1372 int target_step = M_IMGDATA->m_width;
1373
1374 for (int j = 0; j < height; j++,
1375 source_data += source_step,
1376 target_data += target_step)
1377 {
1378 memcpy( target_data, source_data, width );
1379 }
1380 }
1381
1382 if (!HasMask() && image.HasMask())
1383 {
1384 unsigned char r = image.GetMaskRed();
1385 unsigned char g = image.GetMaskGreen();
1386 unsigned char b = image.GetMaskBlue();
1387
1388 unsigned char* source_data = image.GetData() + xx*3 + yy*3*image.GetWidth();
1389 int source_step = image.GetWidth()*3;
1390
1391 unsigned char* target_data = GetData() + (x+xx)*3 + (y+yy)*3*M_IMGDATA->m_width;
1392 int target_step = M_IMGDATA->m_width*3;
1393
1394 for (int j = 0; j < height; j++)
1395 {
1396 for (int i = 0; i < width*3; i+=3)
1397 {
1398 if ((source_data[i] != r) ||
1399 (source_data[i+1] != g) ||
1400 (source_data[i+2] != b))
1401 {
1402 memcpy( target_data+i, source_data+i, 3 );
1403 }
1404 }
1405 source_data += source_step;
1406 target_data += target_step;
1407 }
1408 }
1409 }
1410
1411 void wxImage::Replace( unsigned char r1, unsigned char g1, unsigned char b1,
1412 unsigned char r2, unsigned char g2, unsigned char b2 )
1413 {
1414 wxCHECK_RET( Ok(), wxT("invalid image") );
1415
1416 AllocExclusive();
1417
1418 unsigned char *data = GetData();
1419
1420 const int w = GetWidth();
1421 const int h = GetHeight();
1422
1423 for (int j = 0; j < h; j++)
1424 for (int i = 0; i < w; i++)
1425 {
1426 if ((data[0] == r1) && (data[1] == g1) && (data[2] == b1))
1427 {
1428 data[0] = r2;
1429 data[1] = g2;
1430 data[2] = b2;
1431 }
1432 data += 3;
1433 }
1434 }
1435
1436 wxImage wxImage::ConvertToGreyscale( double lr, double lg, double lb ) const
1437 {
1438 wxImage image;
1439
1440 wxCHECK_MSG( Ok(), image, wxT("invalid image") );
1441
1442 image.Create(M_IMGDATA->m_width, M_IMGDATA->m_height, false);
1443
1444 unsigned char *dest = image.GetData();
1445
1446 wxCHECK_MSG( dest, image, wxT("unable to create image") );
1447
1448 unsigned char *src = M_IMGDATA->m_data;
1449 bool hasMask = M_IMGDATA->m_hasMask;
1450 unsigned char maskRed = M_IMGDATA->m_maskRed;
1451 unsigned char maskGreen = M_IMGDATA->m_maskGreen;
1452 unsigned char maskBlue = M_IMGDATA->m_maskBlue;
1453
1454 if ( hasMask )
1455 image.SetMaskColour(maskRed, maskGreen, maskBlue);
1456
1457 const long size = M_IMGDATA->m_width * M_IMGDATA->m_height;
1458 for ( long i = 0; i < size; i++, src += 3, dest += 3 )
1459 {
1460 // don't modify the mask
1461 if ( hasMask && src[0] == maskRed && src[1] == maskGreen && src[2] == maskBlue )
1462 {
1463 memcpy(dest, src, 3);
1464 }
1465 else
1466 {
1467 // calculate the luma
1468 double luma = (src[0] * lr + src[1] * lg + src[2] * lb) + 0.5;
1469 dest[0] = dest[1] = dest[2] = static_cast<unsigned char>(luma);
1470 }
1471 }
1472
1473 // copy the alpha channel, if any
1474 if (HasAlpha())
1475 {
1476 const size_t alphaSize = GetWidth() * GetHeight();
1477 unsigned char *alpha = (unsigned char*)malloc(alphaSize);
1478 memcpy(alpha, GetAlpha(), alphaSize);
1479 image.InitAlpha();
1480 image.SetAlpha(alpha);
1481 }
1482
1483 return image;
1484 }
1485
1486 wxImage wxImage::ConvertToMono( unsigned char r, unsigned char g, unsigned char b ) const
1487 {
1488 wxImage image;
1489
1490 wxCHECK_MSG( Ok(), image, wxT("invalid image") );
1491
1492 image.Create( M_IMGDATA->m_width, M_IMGDATA->m_height, false );
1493
1494 unsigned char *data = image.GetData();
1495
1496 wxCHECK_MSG( data, image, wxT("unable to create image") );
1497
1498 if (M_IMGDATA->m_hasMask)
1499 {
1500 if (M_IMGDATA->m_maskRed == r && M_IMGDATA->m_maskGreen == g &&
1501 M_IMGDATA->m_maskBlue == b)
1502 image.SetMaskColour( 255, 255, 255 );
1503 else
1504 image.SetMaskColour( 0, 0, 0 );
1505 }
1506
1507 long size = M_IMGDATA->m_height * M_IMGDATA->m_width;
1508
1509 unsigned char *srcd = M_IMGDATA->m_data;
1510 unsigned char *tard = image.GetData();
1511
1512 for ( long i = 0; i < size; i++, srcd += 3, tard += 3 )
1513 {
1514 if (srcd[0] == r && srcd[1] == g && srcd[2] == b)
1515 tard[0] = tard[1] = tard[2] = 255;
1516 else
1517 tard[0] = tard[1] = tard[2] = 0;
1518 }
1519
1520 return image;
1521 }
1522
1523 int wxImage::GetWidth() const
1524 {
1525 wxCHECK_MSG( Ok(), 0, wxT("invalid image") );
1526
1527 return M_IMGDATA->m_width;
1528 }
1529
1530 int wxImage::GetHeight() const
1531 {
1532 wxCHECK_MSG( Ok(), 0, wxT("invalid image") );
1533
1534 return M_IMGDATA->m_height;
1535 }
1536
1537 wxBitmapType wxImage::GetType() const
1538 {
1539 wxCHECK_MSG( IsOk(), wxBITMAP_TYPE_INVALID, wxT("invalid image") );
1540
1541 return M_IMGDATA->m_type;
1542 }
1543
1544 void wxImage::SetType(wxBitmapType type)
1545 {
1546 wxCHECK_RET( IsOk(), "must create the image before setting its type");
1547
1548 // type can be wxBITMAP_TYPE_INVALID to reset the image type to default
1549 wxASSERT_MSG( type != wxBITMAP_TYPE_MAX, "invalid bitmap type" );
1550
1551 M_IMGDATA->m_type = type;
1552 }
1553
1554 long wxImage::XYToIndex(int x, int y) const
1555 {
1556 if ( Ok() &&
1557 x >= 0 && y >= 0 &&
1558 x < M_IMGDATA->m_width && y < M_IMGDATA->m_height )
1559 {
1560 return y*M_IMGDATA->m_width + x;
1561 }
1562
1563 return -1;
1564 }
1565
1566 void wxImage::SetRGB( int x, int y, unsigned char r, unsigned char g, unsigned char b )
1567 {
1568 long pos = XYToIndex(x, y);
1569 wxCHECK_RET( pos != -1, wxT("invalid image coordinates") );
1570
1571 AllocExclusive();
1572
1573 pos *= 3;
1574
1575 M_IMGDATA->m_data[ pos ] = r;
1576 M_IMGDATA->m_data[ pos+1 ] = g;
1577 M_IMGDATA->m_data[ pos+2 ] = b;
1578 }
1579
1580 void wxImage::SetRGB( const wxRect& rect_, unsigned char r, unsigned char g, unsigned char b )
1581 {
1582 wxCHECK_RET( Ok(), wxT("invalid image") );
1583
1584 AllocExclusive();
1585
1586 wxRect rect(rect_);
1587 wxRect imageRect(0, 0, GetWidth(), GetHeight());
1588 if ( rect == wxRect() )
1589 {
1590 rect = imageRect;
1591 }
1592 else
1593 {
1594 wxCHECK_RET( imageRect.Contains(rect.GetTopLeft()) &&
1595 imageRect.Contains(rect.GetBottomRight()),
1596 wxT("invalid bounding rectangle") );
1597 }
1598
1599 int x1 = rect.GetLeft(),
1600 y1 = rect.GetTop(),
1601 x2 = rect.GetRight() + 1,
1602 y2 = rect.GetBottom() + 1;
1603
1604 unsigned char *data wxDUMMY_INITIALIZE(NULL);
1605 int x, y, width = GetWidth();
1606 for (y = y1; y < y2; y++)
1607 {
1608 data = M_IMGDATA->m_data + (y*width + x1)*3;
1609 for (x = x1; x < x2; x++)
1610 {
1611 *data++ = r;
1612 *data++ = g;
1613 *data++ = b;
1614 }
1615 }
1616 }
1617
1618 unsigned char wxImage::GetRed( int x, int y ) const
1619 {
1620 long pos = XYToIndex(x, y);
1621 wxCHECK_MSG( pos != -1, 0, wxT("invalid image coordinates") );
1622
1623 pos *= 3;
1624
1625 return M_IMGDATA->m_data[pos];
1626 }
1627
1628 unsigned char wxImage::GetGreen( int x, int y ) const
1629 {
1630 long pos = XYToIndex(x, y);
1631 wxCHECK_MSG( pos != -1, 0, wxT("invalid image coordinates") );
1632
1633 pos *= 3;
1634
1635 return M_IMGDATA->m_data[pos+1];
1636 }
1637
1638 unsigned char wxImage::GetBlue( int x, int y ) const
1639 {
1640 long pos = XYToIndex(x, y);
1641 wxCHECK_MSG( pos != -1, 0, wxT("invalid image coordinates") );
1642
1643 pos *= 3;
1644
1645 return M_IMGDATA->m_data[pos+2];
1646 }
1647
1648 bool wxImage::IsOk() const
1649 {
1650 // image of 0 width or height can't be considered ok - at least because it
1651 // causes crashes in ConvertToBitmap() if we don't catch it in time
1652 wxImageRefData *data = M_IMGDATA;
1653 return data && data->m_ok && data->m_width && data->m_height;
1654 }
1655
1656 unsigned char *wxImage::GetData() const
1657 {
1658 wxCHECK_MSG( Ok(), (unsigned char *)NULL, wxT("invalid image") );
1659
1660 return M_IMGDATA->m_data;
1661 }
1662
1663 void wxImage::SetData( unsigned char *data, bool static_data )
1664 {
1665 wxCHECK_RET( Ok(), wxT("invalid image") );
1666
1667 wxImageRefData *newRefData = new wxImageRefData();
1668
1669 newRefData->m_width = M_IMGDATA->m_width;
1670 newRefData->m_height = M_IMGDATA->m_height;
1671 newRefData->m_data = data;
1672 newRefData->m_ok = true;
1673 newRefData->m_maskRed = M_IMGDATA->m_maskRed;
1674 newRefData->m_maskGreen = M_IMGDATA->m_maskGreen;
1675 newRefData->m_maskBlue = M_IMGDATA->m_maskBlue;
1676 newRefData->m_hasMask = M_IMGDATA->m_hasMask;
1677 newRefData->m_static = static_data;
1678
1679 UnRef();
1680
1681 m_refData = newRefData;
1682 }
1683
1684 void wxImage::SetData( unsigned char *data, int new_width, int new_height, bool static_data )
1685 {
1686 wxImageRefData *newRefData = new wxImageRefData();
1687
1688 if (m_refData)
1689 {
1690 newRefData->m_width = new_width;
1691 newRefData->m_height = new_height;
1692 newRefData->m_data = data;
1693 newRefData->m_ok = true;
1694 newRefData->m_maskRed = M_IMGDATA->m_maskRed;
1695 newRefData->m_maskGreen = M_IMGDATA->m_maskGreen;
1696 newRefData->m_maskBlue = M_IMGDATA->m_maskBlue;
1697 newRefData->m_hasMask = M_IMGDATA->m_hasMask;
1698 }
1699 else
1700 {
1701 newRefData->m_width = new_width;
1702 newRefData->m_height = new_height;
1703 newRefData->m_data = data;
1704 newRefData->m_ok = true;
1705 }
1706 newRefData->m_static = static_data;
1707
1708 UnRef();
1709
1710 m_refData = newRefData;
1711 }
1712
1713 // ----------------------------------------------------------------------------
1714 // alpha channel support
1715 // ----------------------------------------------------------------------------
1716
1717 void wxImage::SetAlpha(int x, int y, unsigned char alpha)
1718 {
1719 wxCHECK_RET( HasAlpha(), wxT("no alpha channel") );
1720
1721 long pos = XYToIndex(x, y);
1722 wxCHECK_RET( pos != -1, wxT("invalid image coordinates") );
1723
1724 AllocExclusive();
1725
1726 M_IMGDATA->m_alpha[pos] = alpha;
1727 }
1728
1729 unsigned char wxImage::GetAlpha(int x, int y) const
1730 {
1731 wxCHECK_MSG( HasAlpha(), 0, wxT("no alpha channel") );
1732
1733 long pos = XYToIndex(x, y);
1734 wxCHECK_MSG( pos != -1, 0, wxT("invalid image coordinates") );
1735
1736 return M_IMGDATA->m_alpha[pos];
1737 }
1738
1739 bool
1740 wxImage::ConvertColourToAlpha(unsigned char r, unsigned char g, unsigned char b)
1741 {
1742 SetAlpha(NULL);
1743
1744 const int w = M_IMGDATA->m_width;
1745 const int h = M_IMGDATA->m_height;
1746
1747 unsigned char *alpha = GetAlpha();
1748 unsigned char *data = GetData();
1749
1750 for ( int y = 0; y < h; y++ )
1751 {
1752 for ( int x = 0; x < w; x++ )
1753 {
1754 *alpha++ = *data;
1755 *data++ = r;
1756 *data++ = g;
1757 *data++ = b;
1758 }
1759 }
1760
1761 return true;
1762 }
1763
1764 void wxImage::SetAlpha( unsigned char *alpha, bool static_data )
1765 {
1766 wxCHECK_RET( Ok(), wxT("invalid image") );
1767
1768 AllocExclusive();
1769
1770 if ( !alpha )
1771 {
1772 alpha = (unsigned char *)malloc(M_IMGDATA->m_width*M_IMGDATA->m_height);
1773 }
1774
1775 if( !M_IMGDATA->m_staticAlpha )
1776 free(M_IMGDATA->m_alpha);
1777
1778 M_IMGDATA->m_alpha = alpha;
1779 M_IMGDATA->m_staticAlpha = static_data;
1780 }
1781
1782 unsigned char *wxImage::GetAlpha() const
1783 {
1784 wxCHECK_MSG( Ok(), (unsigned char *)NULL, wxT("invalid image") );
1785
1786 return M_IMGDATA->m_alpha;
1787 }
1788
1789 void wxImage::InitAlpha()
1790 {
1791 wxCHECK_RET( !HasAlpha(), wxT("image already has an alpha channel") );
1792
1793 // initialize memory for alpha channel
1794 SetAlpha();
1795
1796 unsigned char *alpha = M_IMGDATA->m_alpha;
1797 const size_t lenAlpha = M_IMGDATA->m_width * M_IMGDATA->m_height;
1798
1799 if ( HasMask() )
1800 {
1801 // use the mask to initialize the alpha channel.
1802 const unsigned char * const alphaEnd = alpha + lenAlpha;
1803
1804 const unsigned char mr = M_IMGDATA->m_maskRed;
1805 const unsigned char mg = M_IMGDATA->m_maskGreen;
1806 const unsigned char mb = M_IMGDATA->m_maskBlue;
1807 for ( unsigned char *src = M_IMGDATA->m_data;
1808 alpha < alphaEnd;
1809 src += 3, alpha++ )
1810 {
1811 *alpha = (src[0] == mr && src[1] == mg && src[2] == mb)
1812 ? wxIMAGE_ALPHA_TRANSPARENT
1813 : wxIMAGE_ALPHA_OPAQUE;
1814 }
1815
1816 M_IMGDATA->m_hasMask = false;
1817 }
1818 else // no mask
1819 {
1820 // make the image fully opaque
1821 memset(alpha, wxIMAGE_ALPHA_OPAQUE, lenAlpha);
1822 }
1823 }
1824
1825 // ----------------------------------------------------------------------------
1826 // mask support
1827 // ----------------------------------------------------------------------------
1828
1829 void wxImage::SetMaskColour( unsigned char r, unsigned char g, unsigned char b )
1830 {
1831 wxCHECK_RET( Ok(), wxT("invalid image") );
1832
1833 AllocExclusive();
1834
1835 M_IMGDATA->m_maskRed = r;
1836 M_IMGDATA->m_maskGreen = g;
1837 M_IMGDATA->m_maskBlue = b;
1838 M_IMGDATA->m_hasMask = true;
1839 }
1840
1841 bool wxImage::GetOrFindMaskColour( unsigned char *r, unsigned char *g, unsigned char *b ) const
1842 {
1843 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
1844
1845 if (M_IMGDATA->m_hasMask)
1846 {
1847 if (r) *r = M_IMGDATA->m_maskRed;
1848 if (g) *g = M_IMGDATA->m_maskGreen;
1849 if (b) *b = M_IMGDATA->m_maskBlue;
1850 return true;
1851 }
1852 else
1853 {
1854 FindFirstUnusedColour(r, g, b);
1855 return false;
1856 }
1857 }
1858
1859 unsigned char wxImage::GetMaskRed() const
1860 {
1861 wxCHECK_MSG( Ok(), 0, wxT("invalid image") );
1862
1863 return M_IMGDATA->m_maskRed;
1864 }
1865
1866 unsigned char wxImage::GetMaskGreen() const
1867 {
1868 wxCHECK_MSG( Ok(), 0, wxT("invalid image") );
1869
1870 return M_IMGDATA->m_maskGreen;
1871 }
1872
1873 unsigned char wxImage::GetMaskBlue() const
1874 {
1875 wxCHECK_MSG( Ok(), 0, wxT("invalid image") );
1876
1877 return M_IMGDATA->m_maskBlue;
1878 }
1879
1880 void wxImage::SetMask( bool mask )
1881 {
1882 wxCHECK_RET( Ok(), wxT("invalid image") );
1883
1884 AllocExclusive();
1885
1886 M_IMGDATA->m_hasMask = mask;
1887 }
1888
1889 bool wxImage::HasMask() const
1890 {
1891 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
1892
1893 return M_IMGDATA->m_hasMask;
1894 }
1895
1896 bool wxImage::IsTransparent(int x, int y, unsigned char threshold) const
1897 {
1898 long pos = XYToIndex(x, y);
1899 wxCHECK_MSG( pos != -1, false, wxT("invalid image coordinates") );
1900
1901 // check mask
1902 if ( M_IMGDATA->m_hasMask )
1903 {
1904 const unsigned char *p = M_IMGDATA->m_data + 3*pos;
1905 if ( p[0] == M_IMGDATA->m_maskRed &&
1906 p[1] == M_IMGDATA->m_maskGreen &&
1907 p[2] == M_IMGDATA->m_maskBlue )
1908 {
1909 return true;
1910 }
1911 }
1912
1913 // then check alpha
1914 if ( M_IMGDATA->m_alpha )
1915 {
1916 if ( M_IMGDATA->m_alpha[pos] < threshold )
1917 {
1918 // transparent enough
1919 return true;
1920 }
1921 }
1922
1923 // not transparent
1924 return false;
1925 }
1926
1927 bool wxImage::SetMaskFromImage(const wxImage& mask,
1928 unsigned char mr, unsigned char mg, unsigned char mb)
1929 {
1930 // check that the images are the same size
1931 if ( (M_IMGDATA->m_height != mask.GetHeight() ) || (M_IMGDATA->m_width != mask.GetWidth () ) )
1932 {
1933 wxLogError( _("Image and mask have different sizes.") );
1934 return false;
1935 }
1936
1937 // find unused colour
1938 unsigned char r,g,b ;
1939 if (!FindFirstUnusedColour(&r, &g, &b))
1940 {
1941 wxLogError( _("No unused colour in image being masked.") );
1942 return false ;
1943 }
1944
1945 AllocExclusive();
1946
1947 unsigned char *imgdata = GetData();
1948 unsigned char *maskdata = mask.GetData();
1949
1950 const int w = GetWidth();
1951 const int h = GetHeight();
1952
1953 for (int j = 0; j < h; j++)
1954 {
1955 for (int i = 0; i < w; i++)
1956 {
1957 if ((maskdata[0] == mr) && (maskdata[1] == mg) && (maskdata[2] == mb))
1958 {
1959 imgdata[0] = r;
1960 imgdata[1] = g;
1961 imgdata[2] = b;
1962 }
1963 imgdata += 3;
1964 maskdata += 3;
1965 }
1966 }
1967
1968 SetMaskColour(r, g, b);
1969 SetMask(true);
1970
1971 return true;
1972 }
1973
1974 bool wxImage::ConvertAlphaToMask(unsigned char threshold)
1975 {
1976 if ( !HasAlpha() )
1977 return true;
1978
1979 unsigned char mr, mg, mb;
1980 if ( !FindFirstUnusedColour(&mr, &mg, &mb) )
1981 {
1982 wxLogError( _("No unused colour in image being masked.") );
1983 return false;
1984 }
1985
1986 ConvertAlphaToMask(mr, mg, mb, threshold);
1987 return true;
1988 }
1989
1990 void wxImage::ConvertAlphaToMask(unsigned char mr,
1991 unsigned char mg,
1992 unsigned char mb,
1993 unsigned char threshold)
1994 {
1995 if ( !HasAlpha() )
1996 return;
1997
1998 AllocExclusive();
1999
2000 SetMask(true);
2001 SetMaskColour(mr, mg, mb);
2002
2003 unsigned char *imgdata = GetData();
2004 unsigned char *alphadata = GetAlpha();
2005
2006 int w = GetWidth();
2007 int h = GetHeight();
2008
2009 for (int y = 0; y < h; y++)
2010 {
2011 for (int x = 0; x < w; x++, imgdata += 3, alphadata++)
2012 {
2013 if (*alphadata < threshold)
2014 {
2015 imgdata[0] = mr;
2016 imgdata[1] = mg;
2017 imgdata[2] = mb;
2018 }
2019 }
2020 }
2021
2022 if ( !M_IMGDATA->m_staticAlpha )
2023 free(M_IMGDATA->m_alpha);
2024
2025 M_IMGDATA->m_alpha = NULL;
2026 M_IMGDATA->m_staticAlpha = false;
2027 }
2028
2029 // ----------------------------------------------------------------------------
2030 // Palette functions
2031 // ----------------------------------------------------------------------------
2032
2033 #if wxUSE_PALETTE
2034
2035 bool wxImage::HasPalette() const
2036 {
2037 if (!Ok())
2038 return false;
2039
2040 return M_IMGDATA->m_palette.Ok();
2041 }
2042
2043 const wxPalette& wxImage::GetPalette() const
2044 {
2045 wxCHECK_MSG( Ok(), wxNullPalette, wxT("invalid image") );
2046
2047 return M_IMGDATA->m_palette;
2048 }
2049
2050 void wxImage::SetPalette(const wxPalette& palette)
2051 {
2052 wxCHECK_RET( Ok(), wxT("invalid image") );
2053
2054 AllocExclusive();
2055
2056 M_IMGDATA->m_palette = palette;
2057 }
2058
2059 #endif // wxUSE_PALETTE
2060
2061 // ----------------------------------------------------------------------------
2062 // Option functions (arbitrary name/value mapping)
2063 // ----------------------------------------------------------------------------
2064
2065 void wxImage::SetOption(const wxString& name, const wxString& value)
2066 {
2067 AllocExclusive();
2068
2069 int idx = M_IMGDATA->m_optionNames.Index(name, false);
2070 if ( idx == wxNOT_FOUND )
2071 {
2072 M_IMGDATA->m_optionNames.Add(name);
2073 M_IMGDATA->m_optionValues.Add(value);
2074 }
2075 else
2076 {
2077 M_IMGDATA->m_optionNames[idx] = name;
2078 M_IMGDATA->m_optionValues[idx] = value;
2079 }
2080 }
2081
2082 void wxImage::SetOption(const wxString& name, int value)
2083 {
2084 wxString valStr;
2085 valStr.Printf(wxT("%d"), value);
2086 SetOption(name, valStr);
2087 }
2088
2089 wxString wxImage::GetOption(const wxString& name) const
2090 {
2091 if ( !M_IMGDATA )
2092 return wxEmptyString;
2093
2094 int idx = M_IMGDATA->m_optionNames.Index(name, false);
2095 if ( idx == wxNOT_FOUND )
2096 return wxEmptyString;
2097 else
2098 return M_IMGDATA->m_optionValues[idx];
2099 }
2100
2101 int wxImage::GetOptionInt(const wxString& name) const
2102 {
2103 return wxAtoi(GetOption(name));
2104 }
2105
2106 bool wxImage::HasOption(const wxString& name) const
2107 {
2108 return M_IMGDATA ? M_IMGDATA->m_optionNames.Index(name, false) != wxNOT_FOUND
2109 : false;
2110 }
2111
2112 // ----------------------------------------------------------------------------
2113 // image I/O
2114 // ----------------------------------------------------------------------------
2115
2116 bool wxImage::LoadFile( const wxString& WXUNUSED_UNLESS_STREAMS(filename),
2117 wxBitmapType WXUNUSED_UNLESS_STREAMS(type),
2118 int WXUNUSED_UNLESS_STREAMS(index) )
2119 {
2120 #if HAS_FILE_STREAMS
2121 if (wxFileExists(filename))
2122 {
2123 wxImageFileInputStream stream(filename);
2124 wxBufferedInputStream bstream( stream );
2125 return LoadFile(bstream, type, index);
2126 }
2127 else
2128 {
2129 wxLogError( _("Can't load image from file '%s': file does not exist."), filename.c_str() );
2130
2131 return false;
2132 }
2133 #else // !HAS_FILE_STREAMS
2134 return false;
2135 #endif // HAS_FILE_STREAMS
2136 }
2137
2138 bool wxImage::LoadFile( const wxString& WXUNUSED_UNLESS_STREAMS(filename),
2139 const wxString& WXUNUSED_UNLESS_STREAMS(mimetype),
2140 int WXUNUSED_UNLESS_STREAMS(index) )
2141 {
2142 #if HAS_FILE_STREAMS
2143 if (wxFileExists(filename))
2144 {
2145 wxImageFileInputStream stream(filename);
2146 wxBufferedInputStream bstream( stream );
2147 return LoadFile(bstream, mimetype, index);
2148 }
2149 else
2150 {
2151 wxLogError( _("Can't load image from file '%s': file does not exist."), filename.c_str() );
2152
2153 return false;
2154 }
2155 #else // !HAS_FILE_STREAMS
2156 return false;
2157 #endif // HAS_FILE_STREAMS
2158 }
2159
2160
2161 bool wxImage::SaveFile( const wxString& filename ) const
2162 {
2163 wxString ext = filename.AfterLast('.').Lower();
2164
2165 wxImageHandler *handler = FindHandler(ext, wxBITMAP_TYPE_ANY);
2166 if ( !handler)
2167 {
2168 wxLogError(_("Can't save image to file '%s': unknown extension."),
2169 filename);
2170 return false;
2171 }
2172
2173 return SaveFile(filename, handler->GetType());
2174 }
2175
2176 bool wxImage::SaveFile( const wxString& WXUNUSED_UNLESS_STREAMS(filename),
2177 wxBitmapType WXUNUSED_UNLESS_STREAMS(type) ) const
2178 {
2179 #if HAS_FILE_STREAMS
2180 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
2181
2182 ((wxImage*)this)->SetOption(wxIMAGE_OPTION_FILENAME, filename);
2183
2184 wxImageFileOutputStream stream(filename);
2185
2186 if ( stream.IsOk() )
2187 {
2188 wxBufferedOutputStream bstream( stream );
2189 return SaveFile(bstream, type);
2190 }
2191 #endif // HAS_FILE_STREAMS
2192
2193 return false;
2194 }
2195
2196 bool wxImage::SaveFile( const wxString& WXUNUSED_UNLESS_STREAMS(filename),
2197 const wxString& WXUNUSED_UNLESS_STREAMS(mimetype) ) const
2198 {
2199 #if HAS_FILE_STREAMS
2200 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
2201
2202 ((wxImage*)this)->SetOption(wxIMAGE_OPTION_FILENAME, filename);
2203
2204 wxImageFileOutputStream stream(filename);
2205
2206 if ( stream.IsOk() )
2207 {
2208 wxBufferedOutputStream bstream( stream );
2209 return SaveFile(bstream, mimetype);
2210 }
2211 #endif // HAS_FILE_STREAMS
2212
2213 return false;
2214 }
2215
2216 bool wxImage::CanRead( const wxString& WXUNUSED_UNLESS_STREAMS(name) )
2217 {
2218 #if HAS_FILE_STREAMS
2219 wxImageFileInputStream stream(name);
2220 return CanRead(stream);
2221 #else
2222 return false;
2223 #endif
2224 }
2225
2226 int wxImage::GetImageCount( const wxString& WXUNUSED_UNLESS_STREAMS(name),
2227 wxBitmapType WXUNUSED_UNLESS_STREAMS(type) )
2228 {
2229 #if HAS_FILE_STREAMS
2230 wxImageFileInputStream stream(name);
2231 if (stream.Ok())
2232 return GetImageCount(stream, type);
2233 #endif
2234
2235 return 0;
2236 }
2237
2238 #if wxUSE_STREAMS
2239
2240 bool wxImage::CanRead( wxInputStream &stream )
2241 {
2242 const wxList& list = GetHandlers();
2243
2244 for ( wxList::compatibility_iterator node = list.GetFirst(); node; node = node->GetNext() )
2245 {
2246 wxImageHandler *handler=(wxImageHandler*)node->GetData();
2247 if (handler->CanRead( stream ))
2248 return true;
2249 }
2250
2251 return false;
2252 }
2253
2254 int wxImage::GetImageCount( wxInputStream &stream, wxBitmapType type )
2255 {
2256 wxImageHandler *handler;
2257
2258 if ( type == wxBITMAP_TYPE_ANY )
2259 {
2260 const wxList& list = GetHandlers();
2261
2262 for ( wxList::compatibility_iterator node = list.GetFirst();
2263 node;
2264 node = node->GetNext() )
2265 {
2266 handler = (wxImageHandler*)node->GetData();
2267 if ( handler->CanRead(stream) )
2268 {
2269 const int count = handler->GetImageCount(stream);
2270 if ( count >= 0 )
2271 return count;
2272 }
2273
2274 }
2275
2276 wxLogWarning(_("No handler found for image type."));
2277 return 0;
2278 }
2279
2280 handler = FindHandler(type);
2281
2282 if ( !handler )
2283 {
2284 wxLogWarning(_("No image handler for type %ld defined."), type);
2285 return false;
2286 }
2287
2288 if ( handler->CanRead(stream) )
2289 {
2290 return handler->GetImageCount(stream);
2291 }
2292 else
2293 {
2294 wxLogError(_("Image file is not of type %ld."), type);
2295 return 0;
2296 }
2297 }
2298
2299 bool wxImage::DoLoad(wxImageHandler& handler, wxInputStream& stream, int index)
2300 {
2301 // save the options values which can be clobbered by the handler (e.g. many
2302 // of them call Destroy() before trying to load the file)
2303 const unsigned maxWidth = GetOptionInt(wxIMAGE_OPTION_MAX_WIDTH),
2304 maxHeight = GetOptionInt(wxIMAGE_OPTION_MAX_HEIGHT);
2305
2306 if ( !handler.LoadFile(this, stream, true/*verbose*/, index) )
2307 return false;
2308
2309 M_IMGDATA->m_type = handler.GetType();
2310
2311 // rescale the image to the specified size if needed
2312 if ( maxWidth || maxHeight )
2313 {
2314 const unsigned widthOrig = GetWidth(),
2315 heightOrig = GetHeight();
2316
2317 // this uses the same (trivial) algorithm as the JPEG handler
2318 unsigned width = widthOrig,
2319 height = heightOrig;
2320 while ( (maxWidth && width > maxWidth) ||
2321 (maxHeight && height > maxHeight) )
2322 {
2323 width /= 2;
2324 height /= 2;
2325 }
2326
2327 if ( width != widthOrig || height != heightOrig )
2328 Rescale(width, height, wxIMAGE_QUALITY_HIGH);
2329 }
2330
2331 return true;
2332 }
2333
2334 bool wxImage::LoadFile( wxInputStream& stream, wxBitmapType type, int index )
2335 {
2336 AllocExclusive();
2337
2338 wxImageHandler *handler;
2339
2340 if ( type == wxBITMAP_TYPE_ANY )
2341 {
2342 const wxList& list = GetHandlers();
2343 for ( wxList::compatibility_iterator node = list.GetFirst();
2344 node;
2345 node = node->GetNext() )
2346 {
2347 handler = (wxImageHandler*)node->GetData();
2348 if ( handler->CanRead(stream) && DoLoad(*handler, stream, index) )
2349 return true;
2350 }
2351
2352 wxLogWarning( _("No handler found for image type.") );
2353
2354 return false;
2355 }
2356 //else: have specific type
2357
2358 handler = FindHandler(type);
2359 if ( !handler )
2360 {
2361 wxLogWarning( _("No image handler for type %ld defined."), type );
2362 return false;
2363 }
2364
2365 if ( stream.IsSeekable() && !handler->CanRead(stream) )
2366 {
2367 wxLogError(_("Image file is not of type %ld."), type);
2368 return false;
2369 }
2370
2371 return DoLoad(*handler, stream, index);
2372 }
2373
2374 bool wxImage::LoadFile( wxInputStream& stream, const wxString& mimetype, int index )
2375 {
2376 UnRef();
2377
2378 m_refData = new wxImageRefData;
2379
2380 wxImageHandler *handler = FindHandlerMime(mimetype);
2381
2382 if ( !handler )
2383 {
2384 wxLogWarning( _("No image handler for type %s defined."), mimetype.GetData() );
2385 return false;
2386 }
2387
2388 if ( stream.IsSeekable() && !handler->CanRead(stream) )
2389 {
2390 wxLogError(_("Image file is not of type %s."), mimetype);
2391 return false;
2392 }
2393
2394 return DoLoad(*handler, stream, index);
2395 }
2396
2397 bool wxImage::DoSave(wxImageHandler& handler, wxOutputStream& stream) const
2398 {
2399 wxImage * const self = const_cast<wxImage *>(this);
2400 if ( !handler.SaveFile(self, stream) )
2401 return false;
2402
2403 M_IMGDATA->m_type = handler.GetType();
2404 return true;
2405 }
2406
2407 bool wxImage::SaveFile( wxOutputStream& stream, wxBitmapType type ) const
2408 {
2409 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
2410
2411 wxImageHandler *handler = FindHandler(type);
2412 if ( !handler )
2413 {
2414 wxLogWarning( _("No image handler for type %d defined."), type );
2415 return false;
2416 }
2417
2418 return DoSave(*handler, stream);
2419 }
2420
2421 bool wxImage::SaveFile( wxOutputStream& stream, const wxString& mimetype ) const
2422 {
2423 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
2424
2425 wxImageHandler *handler = FindHandlerMime(mimetype);
2426 if ( !handler )
2427 {
2428 wxLogWarning( _("No image handler for type %s defined."), mimetype.GetData() );
2429 }
2430
2431 return DoSave(*handler, stream);
2432 }
2433
2434 #endif // wxUSE_STREAMS
2435
2436 // ----------------------------------------------------------------------------
2437 // image I/O handlers
2438 // ----------------------------------------------------------------------------
2439
2440 void wxImage::AddHandler( wxImageHandler *handler )
2441 {
2442 // Check for an existing handler of the type being added.
2443 if (FindHandler( handler->GetType() ) == 0)
2444 {
2445 sm_handlers.Append( handler );
2446 }
2447 else
2448 {
2449 // This is not documented behaviour, merely the simplest 'fix'
2450 // for preventing duplicate additions. If someone ever has
2451 // a good reason to add and remove duplicate handlers (and they
2452 // may) we should probably refcount the duplicates.
2453 // also an issue in InsertHandler below.
2454
2455 wxLogDebug( wxT("Adding duplicate image handler for '%s'"),
2456 handler->GetName().c_str() );
2457 delete handler;
2458 }
2459 }
2460
2461 void wxImage::InsertHandler( wxImageHandler *handler )
2462 {
2463 // Check for an existing handler of the type being added.
2464 if (FindHandler( handler->GetType() ) == 0)
2465 {
2466 sm_handlers.Insert( handler );
2467 }
2468 else
2469 {
2470 // see AddHandler for additional comments.
2471 wxLogDebug( wxT("Inserting duplicate image handler for '%s'"),
2472 handler->GetName().c_str() );
2473 delete handler;
2474 }
2475 }
2476
2477 bool wxImage::RemoveHandler( const wxString& name )
2478 {
2479 wxImageHandler *handler = FindHandler(name);
2480 if (handler)
2481 {
2482 sm_handlers.DeleteObject(handler);
2483 delete handler;
2484 return true;
2485 }
2486 else
2487 return false;
2488 }
2489
2490 wxImageHandler *wxImage::FindHandler( const wxString& name )
2491 {
2492 wxList::compatibility_iterator node = sm_handlers.GetFirst();
2493 while (node)
2494 {
2495 wxImageHandler *handler = (wxImageHandler*)node->GetData();
2496 if (handler->GetName().Cmp(name) == 0) return handler;
2497
2498 node = node->GetNext();
2499 }
2500 return NULL;
2501 }
2502
2503 wxImageHandler *wxImage::FindHandler( const wxString& extension, wxBitmapType bitmapType )
2504 {
2505 wxList::compatibility_iterator node = sm_handlers.GetFirst();
2506 while (node)
2507 {
2508 wxImageHandler *handler = (wxImageHandler*)node->GetData();
2509 if ((bitmapType == wxBITMAP_TYPE_ANY) || (handler->GetType() == bitmapType))
2510 {
2511 if (handler->GetExtension() == extension)
2512 return handler;
2513 if (handler->GetAltExtensions().Index(extension, false) != wxNOT_FOUND)
2514 return handler;
2515 }
2516 node = node->GetNext();
2517 }
2518 return NULL;
2519 }
2520
2521 wxImageHandler *wxImage::FindHandler(wxBitmapType bitmapType )
2522 {
2523 wxList::compatibility_iterator node = sm_handlers.GetFirst();
2524 while (node)
2525 {
2526 wxImageHandler *handler = (wxImageHandler *)node->GetData();
2527 if (handler->GetType() == bitmapType) return handler;
2528 node = node->GetNext();
2529 }
2530 return NULL;
2531 }
2532
2533 wxImageHandler *wxImage::FindHandlerMime( const wxString& mimetype )
2534 {
2535 wxList::compatibility_iterator node = sm_handlers.GetFirst();
2536 while (node)
2537 {
2538 wxImageHandler *handler = (wxImageHandler *)node->GetData();
2539 if (handler->GetMimeType().IsSameAs(mimetype, false)) return handler;
2540 node = node->GetNext();
2541 }
2542 return NULL;
2543 }
2544
2545 void wxImage::InitStandardHandlers()
2546 {
2547 #if wxUSE_STREAMS
2548 AddHandler(new wxBMPHandler);
2549 #endif // wxUSE_STREAMS
2550 }
2551
2552 void wxImage::CleanUpHandlers()
2553 {
2554 wxList::compatibility_iterator node = sm_handlers.GetFirst();
2555 while (node)
2556 {
2557 wxImageHandler *handler = (wxImageHandler *)node->GetData();
2558 wxList::compatibility_iterator next = node->GetNext();
2559 delete handler;
2560 node = next;
2561 }
2562
2563 sm_handlers.Clear();
2564 }
2565
2566 wxString wxImage::GetImageExtWildcard()
2567 {
2568 wxString fmts;
2569
2570 wxList& Handlers = wxImage::GetHandlers();
2571 wxList::compatibility_iterator Node = Handlers.GetFirst();
2572 while ( Node )
2573 {
2574 wxImageHandler* Handler = (wxImageHandler*)Node->GetData();
2575 fmts += wxT("*.") + Handler->GetExtension();
2576 for (size_t i = 0; i < Handler->GetAltExtensions().size(); i++)
2577 fmts += wxT(";*.") + Handler->GetAltExtensions()[i];
2578 Node = Node->GetNext();
2579 if ( Node ) fmts += wxT(";");
2580 }
2581
2582 return wxT("(") + fmts + wxT(")|") + fmts;
2583 }
2584
2585 wxImage::HSVValue wxImage::RGBtoHSV(const RGBValue& rgb)
2586 {
2587 const double red = rgb.red / 255.0,
2588 green = rgb.green / 255.0,
2589 blue = rgb.blue / 255.0;
2590
2591 // find the min and max intensity (and remember which one was it for the
2592 // latter)
2593 double minimumRGB = red;
2594 if ( green < minimumRGB )
2595 minimumRGB = green;
2596 if ( blue < minimumRGB )
2597 minimumRGB = blue;
2598
2599 enum { RED, GREEN, BLUE } chMax = RED;
2600 double maximumRGB = red;
2601 if ( green > maximumRGB )
2602 {
2603 chMax = GREEN;
2604 maximumRGB = green;
2605 }
2606 if ( blue > maximumRGB )
2607 {
2608 chMax = BLUE;
2609 maximumRGB = blue;
2610 }
2611
2612 const double value = maximumRGB;
2613
2614 double hue = 0.0, saturation;
2615 const double deltaRGB = maximumRGB - minimumRGB;
2616 if ( wxIsNullDouble(deltaRGB) )
2617 {
2618 // Gray has no color
2619 hue = 0.0;
2620 saturation = 0.0;
2621 }
2622 else
2623 {
2624 switch ( chMax )
2625 {
2626 case RED:
2627 hue = (green - blue) / deltaRGB;
2628 break;
2629
2630 case GREEN:
2631 hue = 2.0 + (blue - red) / deltaRGB;
2632 break;
2633
2634 case BLUE:
2635 hue = 4.0 + (red - green) / deltaRGB;
2636 break;
2637
2638 default:
2639 wxFAIL_MSG(wxT("hue not specified"));
2640 break;
2641 }
2642
2643 hue /= 6.0;
2644
2645 if ( hue < 0.0 )
2646 hue += 1.0;
2647
2648 saturation = deltaRGB / maximumRGB;
2649 }
2650
2651 return HSVValue(hue, saturation, value);
2652 }
2653
2654 wxImage::RGBValue wxImage::HSVtoRGB(const HSVValue& hsv)
2655 {
2656 double red, green, blue;
2657
2658 if ( wxIsNullDouble(hsv.saturation) )
2659 {
2660 // Grey
2661 red = hsv.value;
2662 green = hsv.value;
2663 blue = hsv.value;
2664 }
2665 else // not grey
2666 {
2667 double hue = hsv.hue * 6.0; // sector 0 to 5
2668 int i = (int)floor(hue);
2669 double f = hue - i; // fractional part of h
2670 double p = hsv.value * (1.0 - hsv.saturation);
2671
2672 switch (i)
2673 {
2674 case 0:
2675 red = hsv.value;
2676 green = hsv.value * (1.0 - hsv.saturation * (1.0 - f));
2677 blue = p;
2678 break;
2679
2680 case 1:
2681 red = hsv.value * (1.0 - hsv.saturation * f);
2682 green = hsv.value;
2683 blue = p;
2684 break;
2685
2686 case 2:
2687 red = p;
2688 green = hsv.value;
2689 blue = hsv.value * (1.0 - hsv.saturation * (1.0 - f));
2690 break;
2691
2692 case 3:
2693 red = p;
2694 green = hsv.value * (1.0 - hsv.saturation * f);
2695 blue = hsv.value;
2696 break;
2697
2698 case 4:
2699 red = hsv.value * (1.0 - hsv.saturation * (1.0 - f));
2700 green = p;
2701 blue = hsv.value;
2702 break;
2703
2704 default: // case 5:
2705 red = hsv.value;
2706 green = p;
2707 blue = hsv.value * (1.0 - hsv.saturation * f);
2708 break;
2709 }
2710 }
2711
2712 return RGBValue((unsigned char)(red * 255.0),
2713 (unsigned char)(green * 255.0),
2714 (unsigned char)(blue * 255.0));
2715 }
2716
2717 /*
2718 * Rotates the hue of each pixel of the image. angle is a double in the range
2719 * -1.0..1.0 where -1.0 is -360 degrees and 1.0 is 360 degrees
2720 */
2721 void wxImage::RotateHue(double angle)
2722 {
2723 AllocExclusive();
2724
2725 unsigned char *srcBytePtr;
2726 unsigned char *dstBytePtr;
2727 unsigned long count;
2728 wxImage::HSVValue hsv;
2729 wxImage::RGBValue rgb;
2730
2731 wxASSERT (angle >= -1.0 && angle <= 1.0);
2732 count = M_IMGDATA->m_width * M_IMGDATA->m_height;
2733 if ( count > 0 && !wxIsNullDouble(angle) )
2734 {
2735 srcBytePtr = M_IMGDATA->m_data;
2736 dstBytePtr = srcBytePtr;
2737 do
2738 {
2739 rgb.red = *srcBytePtr++;
2740 rgb.green = *srcBytePtr++;
2741 rgb.blue = *srcBytePtr++;
2742 hsv = RGBtoHSV(rgb);
2743
2744 hsv.hue = hsv.hue + angle;
2745 if (hsv.hue > 1.0)
2746 hsv.hue = hsv.hue - 1.0;
2747 else if (hsv.hue < 0.0)
2748 hsv.hue = hsv.hue + 1.0;
2749
2750 rgb = HSVtoRGB(hsv);
2751 *dstBytePtr++ = rgb.red;
2752 *dstBytePtr++ = rgb.green;
2753 *dstBytePtr++ = rgb.blue;
2754 } while (--count != 0);
2755 }
2756 }
2757
2758 //-----------------------------------------------------------------------------
2759 // wxImageHandler
2760 //-----------------------------------------------------------------------------
2761
2762 IMPLEMENT_ABSTRACT_CLASS(wxImageHandler,wxObject)
2763
2764 #if wxUSE_STREAMS
2765 int wxImageHandler::GetImageCount( wxInputStream& stream )
2766 {
2767 // NOTE: this code is the same of wxAnimationDecoder::CanRead and
2768 // wxImageHandler::CallDoCanRead
2769
2770 if ( !stream.IsSeekable() )
2771 return false; // can't test unseekable stream
2772
2773 wxFileOffset posOld = stream.TellI();
2774 int n = DoGetImageCount(stream);
2775
2776 // restore the old position to be able to test other formats and so on
2777 if ( stream.SeekI(posOld) == wxInvalidOffset )
2778 {
2779 wxLogDebug(wxT("Failed to rewind the stream in wxImageHandler!"));
2780
2781 // reading would fail anyhow as we're not at the right position
2782 return false;
2783 }
2784
2785 return n;
2786 }
2787
2788 bool wxImageHandler::CanRead( const wxString& name )
2789 {
2790 if (wxFileExists(name))
2791 {
2792 wxImageFileInputStream stream(name);
2793 return CanRead(stream);
2794 }
2795
2796 wxLogError( _("Can't check image format of file '%s': file does not exist."), name.c_str() );
2797
2798 return false;
2799 }
2800
2801 bool wxImageHandler::CallDoCanRead(wxInputStream& stream)
2802 {
2803 // NOTE: this code is the same of wxAnimationDecoder::CanRead and
2804 // wxImageHandler::GetImageCount
2805
2806 if ( !stream.IsSeekable() )
2807 return false; // can't test unseekable stream
2808
2809 wxFileOffset posOld = stream.TellI();
2810 bool ok = DoCanRead(stream);
2811
2812 // restore the old position to be able to test other formats and so on
2813 if ( stream.SeekI(posOld) == wxInvalidOffset )
2814 {
2815 wxLogDebug(wxT("Failed to rewind the stream in wxImageHandler!"));
2816
2817 // reading would fail anyhow as we're not at the right position
2818 return false;
2819 }
2820
2821 return ok;
2822 }
2823
2824 #endif // wxUSE_STREAMS
2825
2826 /* static */
2827 wxImageResolution
2828 wxImageHandler::GetResolutionFromOptions(const wxImage& image, int *x, int *y)
2829 {
2830 wxCHECK_MSG( x && y, wxIMAGE_RESOLUTION_NONE, wxT("NULL pointer") );
2831
2832 if ( image.HasOption(wxIMAGE_OPTION_RESOLUTIONX) &&
2833 image.HasOption(wxIMAGE_OPTION_RESOLUTIONY) )
2834 {
2835 *x = image.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONX);
2836 *y = image.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONY);
2837 }
2838 else if ( image.HasOption(wxIMAGE_OPTION_RESOLUTION) )
2839 {
2840 *x =
2841 *y = image.GetOptionInt(wxIMAGE_OPTION_RESOLUTION);
2842 }
2843 else // no resolution options specified
2844 {
2845 *x =
2846 *y = 0;
2847
2848 return wxIMAGE_RESOLUTION_NONE;
2849 }
2850
2851 // get the resolution unit too
2852 int resUnit = image.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONUNIT);
2853 if ( !resUnit )
2854 {
2855 // this is the default
2856 resUnit = wxIMAGE_RESOLUTION_INCHES;
2857 }
2858
2859 return (wxImageResolution)resUnit;
2860 }
2861
2862 // ----------------------------------------------------------------------------
2863 // image histogram stuff
2864 // ----------------------------------------------------------------------------
2865
2866 bool
2867 wxImageHistogram::FindFirstUnusedColour(unsigned char *r,
2868 unsigned char *g,
2869 unsigned char *b,
2870 unsigned char r2,
2871 unsigned char b2,
2872 unsigned char g2) const
2873 {
2874 unsigned long key = MakeKey(r2, g2, b2);
2875
2876 while ( find(key) != end() )
2877 {
2878 // color already used
2879 r2++;
2880 if ( r2 >= 255 )
2881 {
2882 r2 = 0;
2883 g2++;
2884 if ( g2 >= 255 )
2885 {
2886 g2 = 0;
2887 b2++;
2888 if ( b2 >= 255 )
2889 {
2890 wxLogError(_("No unused colour in image.") );
2891 return false;
2892 }
2893 }
2894 }
2895
2896 key = MakeKey(r2, g2, b2);
2897 }
2898
2899 if ( r )
2900 *r = r2;
2901 if ( g )
2902 *g = g2;
2903 if ( b )
2904 *b = b2;
2905
2906 return true;
2907 }
2908
2909 bool
2910 wxImage::FindFirstUnusedColour(unsigned char *r,
2911 unsigned char *g,
2912 unsigned char *b,
2913 unsigned char r2,
2914 unsigned char b2,
2915 unsigned char g2) const
2916 {
2917 wxImageHistogram histogram;
2918
2919 ComputeHistogram(histogram);
2920
2921 return histogram.FindFirstUnusedColour(r, g, b, r2, g2, b2);
2922 }
2923
2924
2925
2926 // GRG, Dic/99
2927 // Counts and returns the number of different colours. Optionally stops
2928 // when it exceeds 'stopafter' different colours. This is useful, for
2929 // example, to see if the image can be saved as 8-bit (256 colour or
2930 // less, in this case it would be invoked as CountColours(256)). Default
2931 // value for stopafter is -1 (don't care).
2932 //
2933 unsigned long wxImage::CountColours( unsigned long stopafter ) const
2934 {
2935 wxHashTable h;
2936 wxObject dummy;
2937 unsigned char r, g, b;
2938 unsigned char *p;
2939 unsigned long size, nentries, key;
2940
2941 p = GetData();
2942 size = GetWidth() * GetHeight();
2943 nentries = 0;
2944
2945 for (unsigned long j = 0; (j < size) && (nentries <= stopafter) ; j++)
2946 {
2947 r = *(p++);
2948 g = *(p++);
2949 b = *(p++);
2950 key = wxImageHistogram::MakeKey(r, g, b);
2951
2952 if (h.Get(key) == NULL)
2953 {
2954 h.Put(key, &dummy);
2955 nentries++;
2956 }
2957 }
2958
2959 return nentries;
2960 }
2961
2962
2963 unsigned long wxImage::ComputeHistogram( wxImageHistogram &h ) const
2964 {
2965 unsigned char *p = GetData();
2966 unsigned long nentries = 0;
2967
2968 h.clear();
2969
2970 const unsigned long size = GetWidth() * GetHeight();
2971
2972 unsigned char r, g, b;
2973 for ( unsigned long n = 0; n < size; n++ )
2974 {
2975 r = *p++;
2976 g = *p++;
2977 b = *p++;
2978
2979 wxImageHistogramEntry& entry = h[wxImageHistogram::MakeKey(r, g, b)];
2980
2981 if ( entry.value++ == 0 )
2982 entry.index = nentries++;
2983 }
2984
2985 return nentries;
2986 }
2987
2988 /*
2989 * Rotation code by Carlos Moreno
2990 */
2991
2992 static const double wxROTATE_EPSILON = 1e-10;
2993
2994 // Auxiliary function to rotate a point (x,y) with respect to point p0
2995 // make it inline and use a straight return to facilitate optimization
2996 // also, the function receives the sine and cosine of the angle to avoid
2997 // repeating the time-consuming calls to these functions -- sin/cos can
2998 // be computed and stored in the calling function.
2999
3000 static inline wxRealPoint
3001 wxRotatePoint(const wxRealPoint& p, double cos_angle, double sin_angle,
3002 const wxRealPoint& p0)
3003 {
3004 return wxRealPoint(p0.x + (p.x - p0.x) * cos_angle - (p.y - p0.y) * sin_angle,
3005 p0.y + (p.y - p0.y) * cos_angle + (p.x - p0.x) * sin_angle);
3006 }
3007
3008 static inline wxRealPoint
3009 wxRotatePoint(double x, double y, double cos_angle, double sin_angle,
3010 const wxRealPoint & p0)
3011 {
3012 return wxRotatePoint (wxRealPoint(x,y), cos_angle, sin_angle, p0);
3013 }
3014
3015 wxImage wxImage::Rotate(double angle,
3016 const wxPoint& centre_of_rotation,
3017 bool interpolating,
3018 wxPoint *offset_after_rotation) const
3019 {
3020 // screen coordinates are a mirror image of "real" coordinates
3021 angle = -angle;
3022
3023 const bool has_alpha = HasAlpha();
3024
3025 const int w = GetWidth();
3026 const int h = GetHeight();
3027
3028 int i;
3029
3030 // Create pointer-based array to accelerate access to wxImage's data
3031 unsigned char ** data = new unsigned char * [h];
3032 data[0] = GetData();
3033 for (i = 1; i < h; i++)
3034 data[i] = data[i - 1] + (3 * w);
3035
3036 // Same for alpha channel
3037 unsigned char ** alpha = NULL;
3038 if (has_alpha)
3039 {
3040 alpha = new unsigned char * [h];
3041 alpha[0] = GetAlpha();
3042 for (i = 1; i < h; i++)
3043 alpha[i] = alpha[i - 1] + w;
3044 }
3045
3046 // precompute coefficients for rotation formula
3047 const double cos_angle = cos(angle);
3048 const double sin_angle = sin(angle);
3049
3050 // Create new Image to store the result
3051 // First, find rectangle that covers the rotated image; to do that,
3052 // rotate the four corners
3053
3054 const wxRealPoint p0(centre_of_rotation.x, centre_of_rotation.y);
3055
3056 wxRealPoint p1 = wxRotatePoint (0, 0, cos_angle, sin_angle, p0);
3057 wxRealPoint p2 = wxRotatePoint (0, h, cos_angle, sin_angle, p0);
3058 wxRealPoint p3 = wxRotatePoint (w, 0, cos_angle, sin_angle, p0);
3059 wxRealPoint p4 = wxRotatePoint (w, h, cos_angle, sin_angle, p0);
3060
3061 int x1a = (int) floor (wxMin (wxMin(p1.x, p2.x), wxMin(p3.x, p4.x)));
3062 int y1a = (int) floor (wxMin (wxMin(p1.y, p2.y), wxMin(p3.y, p4.y)));
3063 int x2a = (int) ceil (wxMax (wxMax(p1.x, p2.x), wxMax(p3.x, p4.x)));
3064 int y2a = (int) ceil (wxMax (wxMax(p1.y, p2.y), wxMax(p3.y, p4.y)));
3065
3066 // Create rotated image
3067 wxImage rotated (x2a - x1a + 1, y2a - y1a + 1, false);
3068 // With alpha channel
3069 if (has_alpha)
3070 rotated.SetAlpha();
3071
3072 if (offset_after_rotation != NULL)
3073 {
3074 *offset_after_rotation = wxPoint (x1a, y1a);
3075 }
3076
3077 // the rotated (destination) image is always accessed sequentially via this
3078 // pointer, there is no need for pointer-based arrays here
3079 unsigned char *dst = rotated.GetData();
3080
3081 unsigned char *alpha_dst = has_alpha ? rotated.GetAlpha() : NULL;
3082
3083 // if the original image has a mask, use its RGB values as the blank pixel,
3084 // else, fall back to default (black).
3085 unsigned char blank_r = 0;
3086 unsigned char blank_g = 0;
3087 unsigned char blank_b = 0;
3088
3089 if (HasMask())
3090 {
3091 blank_r = GetMaskRed();
3092 blank_g = GetMaskGreen();
3093 blank_b = GetMaskBlue();
3094 rotated.SetMaskColour( blank_r, blank_g, blank_b );
3095 }
3096
3097 // Now, for each point of the rotated image, find where it came from, by
3098 // performing an inverse rotation (a rotation of -angle) and getting the
3099 // pixel at those coordinates
3100
3101 const int rH = rotated.GetHeight();
3102 const int rW = rotated.GetWidth();
3103
3104 // do the (interpolating) test outside of the loops, so that it is done
3105 // only once, instead of repeating it for each pixel.
3106 if (interpolating)
3107 {
3108 for (int y = 0; y < rH; y++)
3109 {
3110 for (int x = 0; x < rW; x++)
3111 {
3112 wxRealPoint src = wxRotatePoint (x + x1a, y + y1a, cos_angle, -sin_angle, p0);
3113
3114 if (-0.25 < src.x && src.x < w - 0.75 &&
3115 -0.25 < src.y && src.y < h - 0.75)
3116 {
3117 // interpolate using the 4 enclosing grid-points. Those
3118 // points can be obtained using floor and ceiling of the
3119 // exact coordinates of the point
3120 int x1, y1, x2, y2;
3121
3122 if (0 < src.x && src.x < w - 1)
3123 {
3124 x1 = wxRound(floor(src.x));
3125 x2 = wxRound(ceil(src.x));
3126 }
3127 else // else means that x is near one of the borders (0 or width-1)
3128 {
3129 x1 = x2 = wxRound (src.x);
3130 }
3131
3132 if (0 < src.y && src.y < h - 1)
3133 {
3134 y1 = wxRound(floor(src.y));
3135 y2 = wxRound(ceil(src.y));
3136 }
3137 else
3138 {
3139 y1 = y2 = wxRound (src.y);
3140 }
3141
3142 // get four points and the distances (square of the distance,
3143 // for efficiency reasons) for the interpolation formula
3144
3145 // GRG: Do not calculate the points until they are
3146 // really needed -- this way we can calculate
3147 // just one, instead of four, if d1, d2, d3
3148 // or d4 are < wxROTATE_EPSILON
3149
3150 const double d1 = (src.x - x1) * (src.x - x1) + (src.y - y1) * (src.y - y1);
3151 const double d2 = (src.x - x2) * (src.x - x2) + (src.y - y1) * (src.y - y1);
3152 const double d3 = (src.x - x2) * (src.x - x2) + (src.y - y2) * (src.y - y2);
3153 const double d4 = (src.x - x1) * (src.x - x1) + (src.y - y2) * (src.y - y2);
3154
3155 // Now interpolate as a weighted average of the four surrounding
3156 // points, where the weights are the distances to each of those points
3157
3158 // If the point is exactly at one point of the grid of the source
3159 // image, then don't interpolate -- just assign the pixel
3160
3161 // d1,d2,d3,d4 are positive -- no need for abs()
3162 if (d1 < wxROTATE_EPSILON)
3163 {
3164 unsigned char *p = data[y1] + (3 * x1);
3165 *(dst++) = *(p++);
3166 *(dst++) = *(p++);
3167 *(dst++) = *p;
3168
3169 if (has_alpha)
3170 *(alpha_dst++) = *(alpha[y1] + x1);
3171 }
3172 else if (d2 < wxROTATE_EPSILON)
3173 {
3174 unsigned char *p = data[y1] + (3 * x2);
3175 *(dst++) = *(p++);
3176 *(dst++) = *(p++);
3177 *(dst++) = *p;
3178
3179 if (has_alpha)
3180 *(alpha_dst++) = *(alpha[y1] + x2);
3181 }
3182 else if (d3 < wxROTATE_EPSILON)
3183 {
3184 unsigned char *p = data[y2] + (3 * x2);
3185 *(dst++) = *(p++);
3186 *(dst++) = *(p++);
3187 *(dst++) = *p;
3188
3189 if (has_alpha)
3190 *(alpha_dst++) = *(alpha[y2] + x2);
3191 }
3192 else if (d4 < wxROTATE_EPSILON)
3193 {
3194 unsigned char *p = data[y2] + (3 * x1);
3195 *(dst++) = *(p++);
3196 *(dst++) = *(p++);
3197 *(dst++) = *p;
3198
3199 if (has_alpha)
3200 *(alpha_dst++) = *(alpha[y2] + x1);
3201 }
3202 else
3203 {
3204 // weights for the weighted average are proportional to the inverse of the distance
3205 unsigned char *v1 = data[y1] + (3 * x1);
3206 unsigned char *v2 = data[y1] + (3 * x2);
3207 unsigned char *v3 = data[y2] + (3 * x2);
3208 unsigned char *v4 = data[y2] + (3 * x1);
3209
3210 const double w1 = 1/d1, w2 = 1/d2, w3 = 1/d3, w4 = 1/d4;
3211
3212 // GRG: Unrolled.
3213
3214 *(dst++) = (unsigned char)
3215 ( (w1 * *(v1++) + w2 * *(v2++) +
3216 w3 * *(v3++) + w4 * *(v4++)) /
3217 (w1 + w2 + w3 + w4) );
3218 *(dst++) = (unsigned char)
3219 ( (w1 * *(v1++) + w2 * *(v2++) +
3220 w3 * *(v3++) + w4 * *(v4++)) /
3221 (w1 + w2 + w3 + w4) );
3222 *(dst++) = (unsigned char)
3223 ( (w1 * *v1 + w2 * *v2 +
3224 w3 * *v3 + w4 * *v4) /
3225 (w1 + w2 + w3 + w4) );
3226
3227 if (has_alpha)
3228 {
3229 v1 = alpha[y1] + (x1);
3230 v2 = alpha[y1] + (x2);
3231 v3 = alpha[y2] + (x2);
3232 v4 = alpha[y2] + (x1);
3233
3234 *(alpha_dst++) = (unsigned char)
3235 ( (w1 * *v1 + w2 * *v2 +
3236 w3 * *v3 + w4 * *v4) /
3237 (w1 + w2 + w3 + w4) );
3238 }
3239 }
3240 }
3241 else
3242 {
3243 *(dst++) = blank_r;
3244 *(dst++) = blank_g;
3245 *(dst++) = blank_b;
3246
3247 if (has_alpha)
3248 *(alpha_dst++) = 0;
3249 }
3250 }
3251 }
3252 }
3253 else // not interpolating
3254 {
3255 for (int y = 0; y < rH; y++)
3256 {
3257 for (int x = 0; x < rW; x++)
3258 {
3259 wxRealPoint src = wxRotatePoint (x + x1a, y + y1a, cos_angle, -sin_angle, p0);
3260
3261 const int xs = wxRound (src.x); // wxRound rounds to the
3262 const int ys = wxRound (src.y); // closest integer
3263
3264 if (0 <= xs && xs < w && 0 <= ys && ys < h)
3265 {
3266 unsigned char *p = data[ys] + (3 * xs);
3267 *(dst++) = *(p++);
3268 *(dst++) = *(p++);
3269 *(dst++) = *p;
3270
3271 if (has_alpha)
3272 *(alpha_dst++) = *(alpha[ys] + (xs));
3273 }
3274 else
3275 {
3276 *(dst++) = blank_r;
3277 *(dst++) = blank_g;
3278 *(dst++) = blank_b;
3279
3280 if (has_alpha)
3281 *(alpha_dst++) = 255;
3282 }
3283 }
3284 }
3285 }
3286
3287 delete [] data;
3288 delete [] alpha;
3289
3290 return rotated;
3291 }
3292
3293
3294
3295
3296
3297 // A module to allow wxImage initialization/cleanup
3298 // without calling these functions from app.cpp or from
3299 // the user's application.
3300
3301 class wxImageModule: public wxModule
3302 {
3303 DECLARE_DYNAMIC_CLASS(wxImageModule)
3304 public:
3305 wxImageModule() {}
3306 bool OnInit() { wxImage::InitStandardHandlers(); return true; }
3307 void OnExit() { wxImage::CleanUpHandlers(); }
3308 };
3309
3310 IMPLEMENT_DYNAMIC_CLASS(wxImageModule, wxModule)
3311
3312
3313 #endif // wxUSE_IMAGE