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