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