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