No changes, just refactor common code in wxImage cloning functions.
[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 unsigned char *source_data = M_IMGDATA->m_data;
338 unsigned char *target_data = data;
339 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 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 unsigned char *source_data = M_IMGDATA->m_data;
503 unsigned char *target_data = data;
504 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 unsigned char* src_line = &source_data[(y>>16)*old_width*3];
528 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 unsigned char* src_pixel = &src_line[(x>>16)*3];
534 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 unsigned char* src_data = M_IMGDATA->m_data;
566 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 unsigned char* src_data = M_IMGDATA->m_data;
640 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 unsigned char* src_data = M_IMGDATA->m_data;
770 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( false ));
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( false ));
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 != NULL)
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 != NULL) {
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 unsigned char* source_data = image.GetData() + xx*3 + yy*3*image.GetWidth();
1401 int source_step = image.GetWidth()*3;
1402
1403 unsigned char* target_data = GetData() + (x+xx)*3 + (y+yy)*3*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 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 unsigned char* source_data = image.GetData() + xx*3 + yy*3*image.GetWidth();
1440 int source_step = image.GetWidth()*3;
1441
1442 unsigned char* target_data = GetData() + (x+xx)*3 + (y+yy)*3*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( false ));
1495
1496 wxCHECK( image.Ok(), image );
1497
1498 const unsigned char *src = M_IMGDATA->m_data;
1499 unsigned char *dest = image.GetData();
1500
1501 bool hasMask = M_IMGDATA->m_hasMask;
1502 unsigned char maskRed = M_IMGDATA->m_maskRed;
1503 unsigned char maskGreen = M_IMGDATA->m_maskGreen;
1504 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 // don't modify the mask
1511 if ( hasMask && src[0] == maskRed && src[1] == maskGreen && src[2] == maskBlue )
1512 {
1513 }
1514 else
1515 {
1516 wxColour::MakeGrey(dest + 0, dest + 1, dest + 2, weight_r, weight_g, weight_b);
1517 }
1518 }
1519
1520 // copy the alpha channel, if any
1521 if ( image.HasAlpha() )
1522 {
1523 memcpy( image.GetAlpha(), GetAlpha(), GetWidth() * GetHeight() );
1524 }
1525
1526 return image;
1527 }
1528
1529 wxImage wxImage::ConvertToMono( unsigned char r, unsigned char g, unsigned char b ) const
1530 {
1531 wxImage image;
1532
1533 wxCHECK_MSG( Ok(), image, wxT("invalid image") );
1534
1535 image.Create( M_IMGDATA->m_width, M_IMGDATA->m_height, false );
1536
1537 unsigned char *data = image.GetData();
1538
1539 wxCHECK_MSG( data, image, wxT("unable to create image") );
1540
1541 if (M_IMGDATA->m_hasMask)
1542 {
1543 if (M_IMGDATA->m_maskRed == r && M_IMGDATA->m_maskGreen == g &&
1544 M_IMGDATA->m_maskBlue == b)
1545 image.SetMaskColour( 255, 255, 255 );
1546 else
1547 image.SetMaskColour( 0, 0, 0 );
1548 }
1549
1550 long size = M_IMGDATA->m_height * M_IMGDATA->m_width;
1551
1552 unsigned char *srcd = M_IMGDATA->m_data;
1553 unsigned char *tard = image.GetData();
1554
1555 for ( long i = 0; i < size; i++, srcd += 3, tard += 3 )
1556 {
1557 bool on = (srcd[0] == r) && (srcd[1] == g) && (srcd[2] == b);
1558 wxColourBase::MakeMono(tard + 0, tard + 1, tard + 2, on);
1559 }
1560
1561 return image;
1562 }
1563
1564 wxImage wxImage::ConvertToDisabled(unsigned char brightness) const
1565 {
1566 wxImage image = *this;
1567
1568 unsigned char mr = image.GetMaskRed();
1569 unsigned char mg = image.GetMaskGreen();
1570 unsigned char mb = image.GetMaskBlue();
1571
1572 int width = image.GetWidth();
1573 int height = image.GetHeight();
1574 bool has_mask = image.HasMask();
1575
1576 for (int y = height-1; y >= 0; --y)
1577 {
1578 for (int x = width-1; x >= 0; --x)
1579 {
1580 unsigned char* data = image.GetData() + (y*(width*3))+(x*3);
1581 unsigned char* r = data;
1582 unsigned char* g = data+1;
1583 unsigned char* b = data+2;
1584
1585 if (has_mask && (*r == mr) && (*g == mg) && (*b == mb))
1586 continue;
1587
1588 wxColour::MakeDisabled(r, g, b, brightness);
1589 }
1590 }
1591 return image;
1592 }
1593
1594 int wxImage::GetWidth() const
1595 {
1596 wxCHECK_MSG( Ok(), 0, wxT("invalid image") );
1597
1598 return M_IMGDATA->m_width;
1599 }
1600
1601 int wxImage::GetHeight() const
1602 {
1603 wxCHECK_MSG( Ok(), 0, wxT("invalid image") );
1604
1605 return M_IMGDATA->m_height;
1606 }
1607
1608 wxBitmapType wxImage::GetType() const
1609 {
1610 wxCHECK_MSG( IsOk(), wxBITMAP_TYPE_INVALID, wxT("invalid image") );
1611
1612 return M_IMGDATA->m_type;
1613 }
1614
1615 void wxImage::SetType(wxBitmapType type)
1616 {
1617 wxCHECK_RET( IsOk(), "must create the image before setting its type");
1618
1619 // type can be wxBITMAP_TYPE_INVALID to reset the image type to default
1620 wxASSERT_MSG( type != wxBITMAP_TYPE_MAX, "invalid bitmap type" );
1621
1622 M_IMGDATA->m_type = type;
1623 }
1624
1625 long wxImage::XYToIndex(int x, int y) const
1626 {
1627 if ( Ok() &&
1628 x >= 0 && y >= 0 &&
1629 x < M_IMGDATA->m_width && y < M_IMGDATA->m_height )
1630 {
1631 return y*M_IMGDATA->m_width + x;
1632 }
1633
1634 return -1;
1635 }
1636
1637 void wxImage::SetRGB( int x, int y, unsigned char r, unsigned char g, unsigned char b )
1638 {
1639 long pos = XYToIndex(x, y);
1640 wxCHECK_RET( pos != -1, wxT("invalid image coordinates") );
1641
1642 AllocExclusive();
1643
1644 pos *= 3;
1645
1646 M_IMGDATA->m_data[ pos ] = r;
1647 M_IMGDATA->m_data[ pos+1 ] = g;
1648 M_IMGDATA->m_data[ pos+2 ] = b;
1649 }
1650
1651 void wxImage::SetRGB( const wxRect& rect_, unsigned char r, unsigned char g, unsigned char b )
1652 {
1653 wxCHECK_RET( Ok(), wxT("invalid image") );
1654
1655 AllocExclusive();
1656
1657 wxRect rect(rect_);
1658 wxRect imageRect(0, 0, GetWidth(), GetHeight());
1659 if ( rect == wxRect() )
1660 {
1661 rect = imageRect;
1662 }
1663 else
1664 {
1665 wxCHECK_RET( imageRect.Contains(rect.GetTopLeft()) &&
1666 imageRect.Contains(rect.GetBottomRight()),
1667 wxT("invalid bounding rectangle") );
1668 }
1669
1670 int x1 = rect.GetLeft(),
1671 y1 = rect.GetTop(),
1672 x2 = rect.GetRight() + 1,
1673 y2 = rect.GetBottom() + 1;
1674
1675 unsigned char *data wxDUMMY_INITIALIZE(NULL);
1676 int x, y, width = GetWidth();
1677 for (y = y1; y < y2; y++)
1678 {
1679 data = M_IMGDATA->m_data + (y*width + x1)*3;
1680 for (x = x1; x < x2; x++)
1681 {
1682 *data++ = r;
1683 *data++ = g;
1684 *data++ = b;
1685 }
1686 }
1687 }
1688
1689 unsigned char wxImage::GetRed( int x, int y ) const
1690 {
1691 long pos = XYToIndex(x, y);
1692 wxCHECK_MSG( pos != -1, 0, wxT("invalid image coordinates") );
1693
1694 pos *= 3;
1695
1696 return M_IMGDATA->m_data[pos];
1697 }
1698
1699 unsigned char wxImage::GetGreen( int x, int y ) const
1700 {
1701 long pos = XYToIndex(x, y);
1702 wxCHECK_MSG( pos != -1, 0, wxT("invalid image coordinates") );
1703
1704 pos *= 3;
1705
1706 return M_IMGDATA->m_data[pos+1];
1707 }
1708
1709 unsigned char wxImage::GetBlue( int x, int y ) const
1710 {
1711 long pos = XYToIndex(x, y);
1712 wxCHECK_MSG( pos != -1, 0, wxT("invalid image coordinates") );
1713
1714 pos *= 3;
1715
1716 return M_IMGDATA->m_data[pos+2];
1717 }
1718
1719 bool wxImage::IsOk() const
1720 {
1721 // image of 0 width or height can't be considered ok - at least because it
1722 // causes crashes in ConvertToBitmap() if we don't catch it in time
1723 wxImageRefData *data = M_IMGDATA;
1724 return data && data->m_ok && data->m_width && data->m_height;
1725 }
1726
1727 unsigned char *wxImage::GetData() const
1728 {
1729 wxCHECK_MSG( Ok(), (unsigned char *)NULL, wxT("invalid image") );
1730
1731 return M_IMGDATA->m_data;
1732 }
1733
1734 void wxImage::SetData( unsigned char *data, bool static_data )
1735 {
1736 wxCHECK_RET( Ok(), wxT("invalid image") );
1737
1738 wxImageRefData *newRefData = new wxImageRefData();
1739
1740 newRefData->m_width = M_IMGDATA->m_width;
1741 newRefData->m_height = M_IMGDATA->m_height;
1742 newRefData->m_data = data;
1743 newRefData->m_ok = true;
1744 newRefData->m_maskRed = M_IMGDATA->m_maskRed;
1745 newRefData->m_maskGreen = M_IMGDATA->m_maskGreen;
1746 newRefData->m_maskBlue = M_IMGDATA->m_maskBlue;
1747 newRefData->m_hasMask = M_IMGDATA->m_hasMask;
1748 newRefData->m_static = static_data;
1749
1750 UnRef();
1751
1752 m_refData = newRefData;
1753 }
1754
1755 void wxImage::SetData( unsigned char *data, int new_width, int new_height, bool static_data )
1756 {
1757 wxImageRefData *newRefData = new wxImageRefData();
1758
1759 if (m_refData)
1760 {
1761 newRefData->m_width = new_width;
1762 newRefData->m_height = new_height;
1763 newRefData->m_data = data;
1764 newRefData->m_ok = true;
1765 newRefData->m_maskRed = M_IMGDATA->m_maskRed;
1766 newRefData->m_maskGreen = M_IMGDATA->m_maskGreen;
1767 newRefData->m_maskBlue = M_IMGDATA->m_maskBlue;
1768 newRefData->m_hasMask = M_IMGDATA->m_hasMask;
1769 }
1770 else
1771 {
1772 newRefData->m_width = new_width;
1773 newRefData->m_height = new_height;
1774 newRefData->m_data = data;
1775 newRefData->m_ok = true;
1776 }
1777 newRefData->m_static = static_data;
1778
1779 UnRef();
1780
1781 m_refData = newRefData;
1782 }
1783
1784 // ----------------------------------------------------------------------------
1785 // alpha channel support
1786 // ----------------------------------------------------------------------------
1787
1788 void wxImage::SetAlpha(int x, int y, unsigned char alpha)
1789 {
1790 wxCHECK_RET( HasAlpha(), wxT("no alpha channel") );
1791
1792 long pos = XYToIndex(x, y);
1793 wxCHECK_RET( pos != -1, wxT("invalid image coordinates") );
1794
1795 AllocExclusive();
1796
1797 M_IMGDATA->m_alpha[pos] = alpha;
1798 }
1799
1800 unsigned char wxImage::GetAlpha(int x, int y) const
1801 {
1802 wxCHECK_MSG( HasAlpha(), 0, wxT("no alpha channel") );
1803
1804 long pos = XYToIndex(x, y);
1805 wxCHECK_MSG( pos != -1, 0, wxT("invalid image coordinates") );
1806
1807 return M_IMGDATA->m_alpha[pos];
1808 }
1809
1810 bool
1811 wxImage::ConvertColourToAlpha(unsigned char r, unsigned char g, unsigned char b)
1812 {
1813 SetAlpha(NULL);
1814
1815 const int w = M_IMGDATA->m_width;
1816 const int h = M_IMGDATA->m_height;
1817
1818 unsigned char *alpha = GetAlpha();
1819 unsigned char *data = GetData();
1820
1821 for ( int y = 0; y < h; y++ )
1822 {
1823 for ( int x = 0; x < w; x++ )
1824 {
1825 *alpha++ = *data;
1826 *data++ = r;
1827 *data++ = g;
1828 *data++ = b;
1829 }
1830 }
1831
1832 return true;
1833 }
1834
1835 void wxImage::SetAlpha( unsigned char *alpha, bool static_data )
1836 {
1837 wxCHECK_RET( Ok(), wxT("invalid image") );
1838
1839 AllocExclusive();
1840
1841 if ( !alpha )
1842 {
1843 alpha = (unsigned char *)malloc(M_IMGDATA->m_width*M_IMGDATA->m_height);
1844 }
1845
1846 if( !M_IMGDATA->m_staticAlpha )
1847 free(M_IMGDATA->m_alpha);
1848
1849 M_IMGDATA->m_alpha = alpha;
1850 M_IMGDATA->m_staticAlpha = static_data;
1851 }
1852
1853 unsigned char *wxImage::GetAlpha() const
1854 {
1855 wxCHECK_MSG( Ok(), (unsigned char *)NULL, wxT("invalid image") );
1856
1857 return M_IMGDATA->m_alpha;
1858 }
1859
1860 void wxImage::InitAlpha()
1861 {
1862 wxCHECK_RET( !HasAlpha(), wxT("image already has an alpha channel") );
1863
1864 // initialize memory for alpha channel
1865 SetAlpha();
1866
1867 unsigned char *alpha = M_IMGDATA->m_alpha;
1868 const size_t lenAlpha = M_IMGDATA->m_width * M_IMGDATA->m_height;
1869
1870 if ( HasMask() )
1871 {
1872 // use the mask to initialize the alpha channel.
1873 const unsigned char * const alphaEnd = alpha + lenAlpha;
1874
1875 const unsigned char mr = M_IMGDATA->m_maskRed;
1876 const unsigned char mg = M_IMGDATA->m_maskGreen;
1877 const unsigned char mb = M_IMGDATA->m_maskBlue;
1878 for ( unsigned char *src = M_IMGDATA->m_data;
1879 alpha < alphaEnd;
1880 src += 3, alpha++ )
1881 {
1882 *alpha = (src[0] == mr && src[1] == mg && src[2] == mb)
1883 ? wxIMAGE_ALPHA_TRANSPARENT
1884 : wxIMAGE_ALPHA_OPAQUE;
1885 }
1886
1887 M_IMGDATA->m_hasMask = false;
1888 }
1889 else // no mask
1890 {
1891 // make the image fully opaque
1892 memset(alpha, wxIMAGE_ALPHA_OPAQUE, lenAlpha);
1893 }
1894 }
1895
1896 void wxImage::ClearAlpha()
1897 {
1898 wxCHECK_RET( HasAlpha(), wxT("image already doesn't have an alpha channel") );
1899
1900 if ( !M_IMGDATA->m_staticAlpha )
1901 free( M_IMGDATA->m_alpha );
1902
1903 M_IMGDATA->m_alpha = NULL;
1904 }
1905
1906
1907 // ----------------------------------------------------------------------------
1908 // mask support
1909 // ----------------------------------------------------------------------------
1910
1911 void wxImage::SetMaskColour( unsigned char r, unsigned char g, unsigned char b )
1912 {
1913 wxCHECK_RET( Ok(), wxT("invalid image") );
1914
1915 AllocExclusive();
1916
1917 M_IMGDATA->m_maskRed = r;
1918 M_IMGDATA->m_maskGreen = g;
1919 M_IMGDATA->m_maskBlue = b;
1920 M_IMGDATA->m_hasMask = true;
1921 }
1922
1923 bool wxImage::GetOrFindMaskColour( unsigned char *r, unsigned char *g, unsigned char *b ) const
1924 {
1925 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
1926
1927 if (M_IMGDATA->m_hasMask)
1928 {
1929 if (r) *r = M_IMGDATA->m_maskRed;
1930 if (g) *g = M_IMGDATA->m_maskGreen;
1931 if (b) *b = M_IMGDATA->m_maskBlue;
1932 return true;
1933 }
1934 else
1935 {
1936 FindFirstUnusedColour(r, g, b);
1937 return false;
1938 }
1939 }
1940
1941 unsigned char wxImage::GetMaskRed() const
1942 {
1943 wxCHECK_MSG( Ok(), 0, wxT("invalid image") );
1944
1945 return M_IMGDATA->m_maskRed;
1946 }
1947
1948 unsigned char wxImage::GetMaskGreen() const
1949 {
1950 wxCHECK_MSG( Ok(), 0, wxT("invalid image") );
1951
1952 return M_IMGDATA->m_maskGreen;
1953 }
1954
1955 unsigned char wxImage::GetMaskBlue() const
1956 {
1957 wxCHECK_MSG( Ok(), 0, wxT("invalid image") );
1958
1959 return M_IMGDATA->m_maskBlue;
1960 }
1961
1962 void wxImage::SetMask( bool mask )
1963 {
1964 wxCHECK_RET( Ok(), wxT("invalid image") );
1965
1966 AllocExclusive();
1967
1968 M_IMGDATA->m_hasMask = mask;
1969 }
1970
1971 bool wxImage::HasMask() const
1972 {
1973 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
1974
1975 return M_IMGDATA->m_hasMask;
1976 }
1977
1978 bool wxImage::IsTransparent(int x, int y, unsigned char threshold) const
1979 {
1980 long pos = XYToIndex(x, y);
1981 wxCHECK_MSG( pos != -1, false, wxT("invalid image coordinates") );
1982
1983 // check mask
1984 if ( M_IMGDATA->m_hasMask )
1985 {
1986 const unsigned char *p = M_IMGDATA->m_data + 3*pos;
1987 if ( p[0] == M_IMGDATA->m_maskRed &&
1988 p[1] == M_IMGDATA->m_maskGreen &&
1989 p[2] == M_IMGDATA->m_maskBlue )
1990 {
1991 return true;
1992 }
1993 }
1994
1995 // then check alpha
1996 if ( M_IMGDATA->m_alpha )
1997 {
1998 if ( M_IMGDATA->m_alpha[pos] < threshold )
1999 {
2000 // transparent enough
2001 return true;
2002 }
2003 }
2004
2005 // not transparent
2006 return false;
2007 }
2008
2009 bool wxImage::SetMaskFromImage(const wxImage& mask,
2010 unsigned char mr, unsigned char mg, unsigned char mb)
2011 {
2012 // check that the images are the same size
2013 if ( (M_IMGDATA->m_height != mask.GetHeight() ) || (M_IMGDATA->m_width != mask.GetWidth () ) )
2014 {
2015 wxLogError( _("Image and mask have different sizes.") );
2016 return false;
2017 }
2018
2019 // find unused colour
2020 unsigned char r,g,b ;
2021 if (!FindFirstUnusedColour(&r, &g, &b))
2022 {
2023 wxLogError( _("No unused colour in image being masked.") );
2024 return false ;
2025 }
2026
2027 AllocExclusive();
2028
2029 unsigned char *imgdata = GetData();
2030 unsigned char *maskdata = mask.GetData();
2031
2032 const int w = GetWidth();
2033 const int h = GetHeight();
2034
2035 for (int j = 0; j < h; j++)
2036 {
2037 for (int i = 0; i < w; i++)
2038 {
2039 if ((maskdata[0] == mr) && (maskdata[1] == mg) && (maskdata[2] == mb))
2040 {
2041 imgdata[0] = r;
2042 imgdata[1] = g;
2043 imgdata[2] = b;
2044 }
2045 imgdata += 3;
2046 maskdata += 3;
2047 }
2048 }
2049
2050 SetMaskColour(r, g, b);
2051 SetMask(true);
2052
2053 return true;
2054 }
2055
2056 bool wxImage::ConvertAlphaToMask(unsigned char threshold)
2057 {
2058 if ( !HasAlpha() )
2059 return false;
2060
2061 unsigned char mr, mg, mb;
2062 if ( !FindFirstUnusedColour(&mr, &mg, &mb) )
2063 {
2064 wxLogError( _("No unused colour in image being masked.") );
2065 return false;
2066 }
2067
2068 return ConvertAlphaToMask(mr, mg, mb, threshold);
2069 }
2070
2071 bool wxImage::ConvertAlphaToMask(unsigned char mr,
2072 unsigned char mg,
2073 unsigned char mb,
2074 unsigned char threshold)
2075 {
2076 if ( !HasAlpha() )
2077 return false;
2078
2079 AllocExclusive();
2080
2081 SetMask(true);
2082 SetMaskColour(mr, mg, mb);
2083
2084 unsigned char *imgdata = GetData();
2085 unsigned char *alphadata = GetAlpha();
2086
2087 int w = GetWidth();
2088 int h = GetHeight();
2089
2090 for (int y = 0; y < h; y++)
2091 {
2092 for (int x = 0; x < w; x++, imgdata += 3, alphadata++)
2093 {
2094 if (*alphadata < threshold)
2095 {
2096 imgdata[0] = mr;
2097 imgdata[1] = mg;
2098 imgdata[2] = mb;
2099 }
2100 }
2101 }
2102
2103 if ( !M_IMGDATA->m_staticAlpha )
2104 free(M_IMGDATA->m_alpha);
2105
2106 M_IMGDATA->m_alpha = NULL;
2107 M_IMGDATA->m_staticAlpha = false;
2108
2109 return true;
2110 }
2111
2112 // ----------------------------------------------------------------------------
2113 // Palette functions
2114 // ----------------------------------------------------------------------------
2115
2116 #if wxUSE_PALETTE
2117
2118 bool wxImage::HasPalette() const
2119 {
2120 if (!Ok())
2121 return false;
2122
2123 return M_IMGDATA->m_palette.Ok();
2124 }
2125
2126 const wxPalette& wxImage::GetPalette() const
2127 {
2128 wxCHECK_MSG( Ok(), wxNullPalette, wxT("invalid image") );
2129
2130 return M_IMGDATA->m_palette;
2131 }
2132
2133 void wxImage::SetPalette(const wxPalette& palette)
2134 {
2135 wxCHECK_RET( Ok(), wxT("invalid image") );
2136
2137 AllocExclusive();
2138
2139 M_IMGDATA->m_palette = palette;
2140 }
2141
2142 #endif // wxUSE_PALETTE
2143
2144 // ----------------------------------------------------------------------------
2145 // Option functions (arbitrary name/value mapping)
2146 // ----------------------------------------------------------------------------
2147
2148 void wxImage::SetOption(const wxString& name, const wxString& value)
2149 {
2150 AllocExclusive();
2151
2152 int idx = M_IMGDATA->m_optionNames.Index(name, false);
2153 if ( idx == wxNOT_FOUND )
2154 {
2155 M_IMGDATA->m_optionNames.Add(name);
2156 M_IMGDATA->m_optionValues.Add(value);
2157 }
2158 else
2159 {
2160 M_IMGDATA->m_optionNames[idx] = name;
2161 M_IMGDATA->m_optionValues[idx] = value;
2162 }
2163 }
2164
2165 void wxImage::SetOption(const wxString& name, int value)
2166 {
2167 wxString valStr;
2168 valStr.Printf(wxT("%d"), value);
2169 SetOption(name, valStr);
2170 }
2171
2172 wxString wxImage::GetOption(const wxString& name) const
2173 {
2174 if ( !M_IMGDATA )
2175 return wxEmptyString;
2176
2177 int idx = M_IMGDATA->m_optionNames.Index(name, false);
2178 if ( idx == wxNOT_FOUND )
2179 return wxEmptyString;
2180 else
2181 return M_IMGDATA->m_optionValues[idx];
2182 }
2183
2184 int wxImage::GetOptionInt(const wxString& name) const
2185 {
2186 return wxAtoi(GetOption(name));
2187 }
2188
2189 bool wxImage::HasOption(const wxString& name) const
2190 {
2191 return M_IMGDATA ? M_IMGDATA->m_optionNames.Index(name, false) != wxNOT_FOUND
2192 : false;
2193 }
2194
2195 // ----------------------------------------------------------------------------
2196 // image I/O
2197 // ----------------------------------------------------------------------------
2198
2199 bool wxImage::LoadFile( const wxString& WXUNUSED_UNLESS_STREAMS(filename),
2200 wxBitmapType WXUNUSED_UNLESS_STREAMS(type),
2201 int WXUNUSED_UNLESS_STREAMS(index) )
2202 {
2203 #if HAS_FILE_STREAMS
2204 if (wxFileExists(filename))
2205 {
2206 wxImageFileInputStream stream(filename);
2207 wxBufferedInputStream bstream( stream );
2208 return LoadFile(bstream, type, index);
2209 }
2210 else
2211 {
2212 wxLogError( _("Can't load image from file '%s': file does not exist."), filename.c_str() );
2213
2214 return false;
2215 }
2216 #else // !HAS_FILE_STREAMS
2217 return false;
2218 #endif // HAS_FILE_STREAMS
2219 }
2220
2221 bool wxImage::LoadFile( const wxString& WXUNUSED_UNLESS_STREAMS(filename),
2222 const wxString& WXUNUSED_UNLESS_STREAMS(mimetype),
2223 int WXUNUSED_UNLESS_STREAMS(index) )
2224 {
2225 #if HAS_FILE_STREAMS
2226 if (wxFileExists(filename))
2227 {
2228 wxImageFileInputStream stream(filename);
2229 wxBufferedInputStream bstream( stream );
2230 return LoadFile(bstream, mimetype, index);
2231 }
2232 else
2233 {
2234 wxLogError( _("Can't load image from file '%s': file does not exist."), filename.c_str() );
2235
2236 return false;
2237 }
2238 #else // !HAS_FILE_STREAMS
2239 return false;
2240 #endif // HAS_FILE_STREAMS
2241 }
2242
2243
2244 bool wxImage::SaveFile( const wxString& filename ) const
2245 {
2246 wxString ext = filename.AfterLast('.').Lower();
2247
2248 wxImageHandler *handler = FindHandler(ext, wxBITMAP_TYPE_ANY);
2249 if ( !handler)
2250 {
2251 wxLogError(_("Can't save image to file '%s': unknown extension."),
2252 filename);
2253 return false;
2254 }
2255
2256 return SaveFile(filename, handler->GetType());
2257 }
2258
2259 bool wxImage::SaveFile( const wxString& WXUNUSED_UNLESS_STREAMS(filename),
2260 wxBitmapType WXUNUSED_UNLESS_STREAMS(type) ) const
2261 {
2262 #if HAS_FILE_STREAMS
2263 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
2264
2265 ((wxImage*)this)->SetOption(wxIMAGE_OPTION_FILENAME, filename);
2266
2267 wxImageFileOutputStream stream(filename);
2268
2269 if ( stream.IsOk() )
2270 {
2271 wxBufferedOutputStream bstream( stream );
2272 return SaveFile(bstream, type);
2273 }
2274 #endif // HAS_FILE_STREAMS
2275
2276 return false;
2277 }
2278
2279 bool wxImage::SaveFile( const wxString& WXUNUSED_UNLESS_STREAMS(filename),
2280 const wxString& WXUNUSED_UNLESS_STREAMS(mimetype) ) const
2281 {
2282 #if HAS_FILE_STREAMS
2283 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
2284
2285 ((wxImage*)this)->SetOption(wxIMAGE_OPTION_FILENAME, filename);
2286
2287 wxImageFileOutputStream stream(filename);
2288
2289 if ( stream.IsOk() )
2290 {
2291 wxBufferedOutputStream bstream( stream );
2292 return SaveFile(bstream, mimetype);
2293 }
2294 #endif // HAS_FILE_STREAMS
2295
2296 return false;
2297 }
2298
2299 bool wxImage::CanRead( const wxString& WXUNUSED_UNLESS_STREAMS(name) )
2300 {
2301 #if HAS_FILE_STREAMS
2302 wxImageFileInputStream stream(name);
2303 return CanRead(stream);
2304 #else
2305 return false;
2306 #endif
2307 }
2308
2309 int wxImage::GetImageCount( const wxString& WXUNUSED_UNLESS_STREAMS(name),
2310 wxBitmapType WXUNUSED_UNLESS_STREAMS(type) )
2311 {
2312 #if HAS_FILE_STREAMS
2313 wxImageFileInputStream stream(name);
2314 if (stream.Ok())
2315 return GetImageCount(stream, type);
2316 #endif
2317
2318 return 0;
2319 }
2320
2321 #if wxUSE_STREAMS
2322
2323 bool wxImage::CanRead( wxInputStream &stream )
2324 {
2325 const wxList& list = GetHandlers();
2326
2327 for ( wxList::compatibility_iterator node = list.GetFirst(); node; node = node->GetNext() )
2328 {
2329 wxImageHandler *handler=(wxImageHandler*)node->GetData();
2330 if (handler->CanRead( stream ))
2331 return true;
2332 }
2333
2334 return false;
2335 }
2336
2337 int wxImage::GetImageCount( wxInputStream &stream, wxBitmapType type )
2338 {
2339 wxImageHandler *handler;
2340
2341 if ( type == wxBITMAP_TYPE_ANY )
2342 {
2343 const wxList& list = GetHandlers();
2344
2345 for ( wxList::compatibility_iterator node = list.GetFirst();
2346 node;
2347 node = node->GetNext() )
2348 {
2349 handler = (wxImageHandler*)node->GetData();
2350 if ( handler->CanRead(stream) )
2351 {
2352 const int count = handler->GetImageCount(stream);
2353 if ( count >= 0 )
2354 return count;
2355 }
2356
2357 }
2358
2359 wxLogWarning(_("No handler found for image type."));
2360 return 0;
2361 }
2362
2363 handler = FindHandler(type);
2364
2365 if ( !handler )
2366 {
2367 wxLogWarning(_("No image handler for type %d defined."), type);
2368 return false;
2369 }
2370
2371 if ( handler->CanRead(stream) )
2372 {
2373 return handler->GetImageCount(stream);
2374 }
2375 else
2376 {
2377 wxLogError(_("Image file is not of type %d."), type);
2378 return 0;
2379 }
2380 }
2381
2382 bool wxImage::DoLoad(wxImageHandler& handler, wxInputStream& stream, int index)
2383 {
2384 // save the options values which can be clobbered by the handler (e.g. many
2385 // of them call Destroy() before trying to load the file)
2386 const unsigned maxWidth = GetOptionInt(wxIMAGE_OPTION_MAX_WIDTH),
2387 maxHeight = GetOptionInt(wxIMAGE_OPTION_MAX_HEIGHT);
2388
2389 if ( !handler.LoadFile(this, stream, true/*verbose*/, index) )
2390 return false;
2391
2392 // rescale the image to the specified size if needed
2393 if ( maxWidth || maxHeight )
2394 {
2395 const unsigned widthOrig = GetWidth(),
2396 heightOrig = GetHeight();
2397
2398 // this uses the same (trivial) algorithm as the JPEG handler
2399 unsigned width = widthOrig,
2400 height = heightOrig;
2401 while ( (maxWidth && width > maxWidth) ||
2402 (maxHeight && height > maxHeight) )
2403 {
2404 width /= 2;
2405 height /= 2;
2406 }
2407
2408 if ( width != widthOrig || height != heightOrig )
2409 Rescale(width, height, wxIMAGE_QUALITY_HIGH);
2410 }
2411
2412 // Set this after Rescale, which currently does not preserve it
2413 M_IMGDATA->m_type = handler.GetType();
2414
2415 return true;
2416 }
2417
2418 bool wxImage::LoadFile( wxInputStream& stream, wxBitmapType type, int index )
2419 {
2420 AllocExclusive();
2421
2422 wxImageHandler *handler;
2423
2424 if ( type == wxBITMAP_TYPE_ANY )
2425 {
2426 const wxList& list = GetHandlers();
2427 for ( wxList::compatibility_iterator node = list.GetFirst();
2428 node;
2429 node = node->GetNext() )
2430 {
2431 handler = (wxImageHandler*)node->GetData();
2432 if ( handler->CanRead(stream) && DoLoad(*handler, stream, index) )
2433 return true;
2434 }
2435
2436 wxLogWarning( _("No handler found for image type.") );
2437
2438 return false;
2439 }
2440 //else: have specific type
2441
2442 handler = FindHandler(type);
2443 if ( !handler )
2444 {
2445 wxLogWarning( _("No image handler for type %d defined."), type );
2446 return false;
2447 }
2448
2449 if ( stream.IsSeekable() && !handler->CanRead(stream) )
2450 {
2451 wxLogError(_("Image file is not of type %d."), type);
2452 return false;
2453 }
2454
2455 return DoLoad(*handler, stream, index);
2456 }
2457
2458 bool wxImage::LoadFile( wxInputStream& stream, const wxString& mimetype, int index )
2459 {
2460 UnRef();
2461
2462 m_refData = new wxImageRefData;
2463
2464 wxImageHandler *handler = FindHandlerMime(mimetype);
2465
2466 if ( !handler )
2467 {
2468 wxLogWarning( _("No image handler for type %s defined."), mimetype.GetData() );
2469 return false;
2470 }
2471
2472 if ( stream.IsSeekable() && !handler->CanRead(stream) )
2473 {
2474 wxLogError(_("Image file is not of type %s."), mimetype);
2475 return false;
2476 }
2477
2478 return DoLoad(*handler, stream, index);
2479 }
2480
2481 bool wxImage::DoSave(wxImageHandler& handler, wxOutputStream& stream) const
2482 {
2483 wxImage * const self = const_cast<wxImage *>(this);
2484 if ( !handler.SaveFile(self, stream) )
2485 return false;
2486
2487 M_IMGDATA->m_type = handler.GetType();
2488 return true;
2489 }
2490
2491 bool wxImage::SaveFile( wxOutputStream& stream, wxBitmapType type ) const
2492 {
2493 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
2494
2495 wxImageHandler *handler = FindHandler(type);
2496 if ( !handler )
2497 {
2498 wxLogWarning( _("No image handler for type %d defined."), type );
2499 return false;
2500 }
2501
2502 return DoSave(*handler, stream);
2503 }
2504
2505 bool wxImage::SaveFile( wxOutputStream& stream, const wxString& mimetype ) const
2506 {
2507 wxCHECK_MSG( Ok(), false, wxT("invalid image") );
2508
2509 wxImageHandler *handler = FindHandlerMime(mimetype);
2510 if ( !handler )
2511 {
2512 wxLogWarning( _("No image handler for type %s defined."), mimetype.GetData() );
2513 }
2514
2515 return DoSave(*handler, stream);
2516 }
2517
2518 #endif // wxUSE_STREAMS
2519
2520 // ----------------------------------------------------------------------------
2521 // image I/O handlers
2522 // ----------------------------------------------------------------------------
2523
2524 void wxImage::AddHandler( wxImageHandler *handler )
2525 {
2526 // Check for an existing handler of the type being added.
2527 if (FindHandler( handler->GetType() ) == 0)
2528 {
2529 sm_handlers.Append( handler );
2530 }
2531 else
2532 {
2533 // This is not documented behaviour, merely the simplest 'fix'
2534 // for preventing duplicate additions. If someone ever has
2535 // a good reason to add and remove duplicate handlers (and they
2536 // may) we should probably refcount the duplicates.
2537 // also an issue in InsertHandler below.
2538
2539 wxLogDebug( wxT("Adding duplicate image handler for '%s'"),
2540 handler->GetName().c_str() );
2541 delete handler;
2542 }
2543 }
2544
2545 void wxImage::InsertHandler( wxImageHandler *handler )
2546 {
2547 // Check for an existing handler of the type being added.
2548 if (FindHandler( handler->GetType() ) == 0)
2549 {
2550 sm_handlers.Insert( handler );
2551 }
2552 else
2553 {
2554 // see AddHandler for additional comments.
2555 wxLogDebug( wxT("Inserting duplicate image handler for '%s'"),
2556 handler->GetName().c_str() );
2557 delete handler;
2558 }
2559 }
2560
2561 bool wxImage::RemoveHandler( const wxString& name )
2562 {
2563 wxImageHandler *handler = FindHandler(name);
2564 if (handler)
2565 {
2566 sm_handlers.DeleteObject(handler);
2567 delete handler;
2568 return true;
2569 }
2570 else
2571 return false;
2572 }
2573
2574 wxImageHandler *wxImage::FindHandler( const wxString& name )
2575 {
2576 wxList::compatibility_iterator node = sm_handlers.GetFirst();
2577 while (node)
2578 {
2579 wxImageHandler *handler = (wxImageHandler*)node->GetData();
2580 if (handler->GetName().Cmp(name) == 0) return handler;
2581
2582 node = node->GetNext();
2583 }
2584 return NULL;
2585 }
2586
2587 wxImageHandler *wxImage::FindHandler( const wxString& extension, wxBitmapType bitmapType )
2588 {
2589 wxList::compatibility_iterator node = sm_handlers.GetFirst();
2590 while (node)
2591 {
2592 wxImageHandler *handler = (wxImageHandler*)node->GetData();
2593 if ((bitmapType == wxBITMAP_TYPE_ANY) || (handler->GetType() == bitmapType))
2594 {
2595 if (handler->GetExtension() == extension)
2596 return handler;
2597 if (handler->GetAltExtensions().Index(extension, false) != wxNOT_FOUND)
2598 return handler;
2599 }
2600 node = node->GetNext();
2601 }
2602 return NULL;
2603 }
2604
2605 wxImageHandler *wxImage::FindHandler(wxBitmapType bitmapType )
2606 {
2607 wxList::compatibility_iterator node = sm_handlers.GetFirst();
2608 while (node)
2609 {
2610 wxImageHandler *handler = (wxImageHandler *)node->GetData();
2611 if (handler->GetType() == bitmapType) return handler;
2612 node = node->GetNext();
2613 }
2614 return NULL;
2615 }
2616
2617 wxImageHandler *wxImage::FindHandlerMime( const wxString& mimetype )
2618 {
2619 wxList::compatibility_iterator node = sm_handlers.GetFirst();
2620 while (node)
2621 {
2622 wxImageHandler *handler = (wxImageHandler *)node->GetData();
2623 if (handler->GetMimeType().IsSameAs(mimetype, false)) return handler;
2624 node = node->GetNext();
2625 }
2626 return NULL;
2627 }
2628
2629 void wxImage::InitStandardHandlers()
2630 {
2631 #if wxUSE_STREAMS
2632 AddHandler(new wxBMPHandler);
2633 #endif // wxUSE_STREAMS
2634 }
2635
2636 void wxImage::CleanUpHandlers()
2637 {
2638 wxList::compatibility_iterator node = sm_handlers.GetFirst();
2639 while (node)
2640 {
2641 wxImageHandler *handler = (wxImageHandler *)node->GetData();
2642 wxList::compatibility_iterator next = node->GetNext();
2643 delete handler;
2644 node = next;
2645 }
2646
2647 sm_handlers.Clear();
2648 }
2649
2650 wxString wxImage::GetImageExtWildcard()
2651 {
2652 wxString fmts;
2653
2654 wxList& Handlers = wxImage::GetHandlers();
2655 wxList::compatibility_iterator Node = Handlers.GetFirst();
2656 while ( Node )
2657 {
2658 wxImageHandler* Handler = (wxImageHandler*)Node->GetData();
2659 fmts += wxT("*.") + Handler->GetExtension();
2660 for (size_t i = 0; i < Handler->GetAltExtensions().size(); i++)
2661 fmts += wxT(";*.") + Handler->GetAltExtensions()[i];
2662 Node = Node->GetNext();
2663 if ( Node ) fmts += wxT(";");
2664 }
2665
2666 return wxT("(") + fmts + wxT(")|") + fmts;
2667 }
2668
2669 wxImage::HSVValue wxImage::RGBtoHSV(const RGBValue& rgb)
2670 {
2671 const double red = rgb.red / 255.0,
2672 green = rgb.green / 255.0,
2673 blue = rgb.blue / 255.0;
2674
2675 // find the min and max intensity (and remember which one was it for the
2676 // latter)
2677 double minimumRGB = red;
2678 if ( green < minimumRGB )
2679 minimumRGB = green;
2680 if ( blue < minimumRGB )
2681 minimumRGB = blue;
2682
2683 enum { RED, GREEN, BLUE } chMax = RED;
2684 double maximumRGB = red;
2685 if ( green > maximumRGB )
2686 {
2687 chMax = GREEN;
2688 maximumRGB = green;
2689 }
2690 if ( blue > maximumRGB )
2691 {
2692 chMax = BLUE;
2693 maximumRGB = blue;
2694 }
2695
2696 const double value = maximumRGB;
2697
2698 double hue = 0.0, saturation;
2699 const double deltaRGB = maximumRGB - minimumRGB;
2700 if ( wxIsNullDouble(deltaRGB) )
2701 {
2702 // Gray has no color
2703 hue = 0.0;
2704 saturation = 0.0;
2705 }
2706 else
2707 {
2708 switch ( chMax )
2709 {
2710 case RED:
2711 hue = (green - blue) / deltaRGB;
2712 break;
2713
2714 case GREEN:
2715 hue = 2.0 + (blue - red) / deltaRGB;
2716 break;
2717
2718 case BLUE:
2719 hue = 4.0 + (red - green) / deltaRGB;
2720 break;
2721
2722 default:
2723 wxFAIL_MSG(wxT("hue not specified"));
2724 break;
2725 }
2726
2727 hue /= 6.0;
2728
2729 if ( hue < 0.0 )
2730 hue += 1.0;
2731
2732 saturation = deltaRGB / maximumRGB;
2733 }
2734
2735 return HSVValue(hue, saturation, value);
2736 }
2737
2738 wxImage::RGBValue wxImage::HSVtoRGB(const HSVValue& hsv)
2739 {
2740 double red, green, blue;
2741
2742 if ( wxIsNullDouble(hsv.saturation) )
2743 {
2744 // Grey
2745 red = hsv.value;
2746 green = hsv.value;
2747 blue = hsv.value;
2748 }
2749 else // not grey
2750 {
2751 double hue = hsv.hue * 6.0; // sector 0 to 5
2752 int i = (int)floor(hue);
2753 double f = hue - i; // fractional part of h
2754 double p = hsv.value * (1.0 - hsv.saturation);
2755
2756 switch (i)
2757 {
2758 case 0:
2759 red = hsv.value;
2760 green = hsv.value * (1.0 - hsv.saturation * (1.0 - f));
2761 blue = p;
2762 break;
2763
2764 case 1:
2765 red = hsv.value * (1.0 - hsv.saturation * f);
2766 green = hsv.value;
2767 blue = p;
2768 break;
2769
2770 case 2:
2771 red = p;
2772 green = hsv.value;
2773 blue = hsv.value * (1.0 - hsv.saturation * (1.0 - f));
2774 break;
2775
2776 case 3:
2777 red = p;
2778 green = hsv.value * (1.0 - hsv.saturation * f);
2779 blue = hsv.value;
2780 break;
2781
2782 case 4:
2783 red = hsv.value * (1.0 - hsv.saturation * (1.0 - f));
2784 green = p;
2785 blue = hsv.value;
2786 break;
2787
2788 default: // case 5:
2789 red = hsv.value;
2790 green = p;
2791 blue = hsv.value * (1.0 - hsv.saturation * f);
2792 break;
2793 }
2794 }
2795
2796 return RGBValue((unsigned char)(red * 255.0),
2797 (unsigned char)(green * 255.0),
2798 (unsigned char)(blue * 255.0));
2799 }
2800
2801 /*
2802 * Rotates the hue of each pixel of the image. angle is a double in the range
2803 * -1.0..1.0 where -1.0 is -360 degrees and 1.0 is 360 degrees
2804 */
2805 void wxImage::RotateHue(double angle)
2806 {
2807 AllocExclusive();
2808
2809 unsigned char *srcBytePtr;
2810 unsigned char *dstBytePtr;
2811 unsigned long count;
2812 wxImage::HSVValue hsv;
2813 wxImage::RGBValue rgb;
2814
2815 wxASSERT (angle >= -1.0 && angle <= 1.0);
2816 count = M_IMGDATA->m_width * M_IMGDATA->m_height;
2817 if ( count > 0 && !wxIsNullDouble(angle) )
2818 {
2819 srcBytePtr = M_IMGDATA->m_data;
2820 dstBytePtr = srcBytePtr;
2821 do
2822 {
2823 rgb.red = *srcBytePtr++;
2824 rgb.green = *srcBytePtr++;
2825 rgb.blue = *srcBytePtr++;
2826 hsv = RGBtoHSV(rgb);
2827
2828 hsv.hue = hsv.hue + angle;
2829 if (hsv.hue > 1.0)
2830 hsv.hue = hsv.hue - 1.0;
2831 else if (hsv.hue < 0.0)
2832 hsv.hue = hsv.hue + 1.0;
2833
2834 rgb = HSVtoRGB(hsv);
2835 *dstBytePtr++ = rgb.red;
2836 *dstBytePtr++ = rgb.green;
2837 *dstBytePtr++ = rgb.blue;
2838 } while (--count != 0);
2839 }
2840 }
2841
2842 //-----------------------------------------------------------------------------
2843 // wxImageHandler
2844 //-----------------------------------------------------------------------------
2845
2846 IMPLEMENT_ABSTRACT_CLASS(wxImageHandler,wxObject)
2847
2848 #if wxUSE_STREAMS
2849 int wxImageHandler::GetImageCount( wxInputStream& stream )
2850 {
2851 // NOTE: this code is the same of wxAnimationDecoder::CanRead and
2852 // wxImageHandler::CallDoCanRead
2853
2854 if ( !stream.IsSeekable() )
2855 return false; // can't test unseekable stream
2856
2857 wxFileOffset posOld = stream.TellI();
2858 int n = DoGetImageCount(stream);
2859
2860 // restore the old position to be able to test other formats and so on
2861 if ( stream.SeekI(posOld) == wxInvalidOffset )
2862 {
2863 wxLogDebug(wxT("Failed to rewind the stream in wxImageHandler!"));
2864
2865 // reading would fail anyhow as we're not at the right position
2866 return false;
2867 }
2868
2869 return n;
2870 }
2871
2872 bool wxImageHandler::CanRead( const wxString& name )
2873 {
2874 if (wxFileExists(name))
2875 {
2876 wxImageFileInputStream stream(name);
2877 return CanRead(stream);
2878 }
2879
2880 wxLogError( _("Can't check image format of file '%s': file does not exist."), name.c_str() );
2881
2882 return false;
2883 }
2884
2885 bool wxImageHandler::CallDoCanRead(wxInputStream& stream)
2886 {
2887 // NOTE: this code is the same of wxAnimationDecoder::CanRead and
2888 // wxImageHandler::GetImageCount
2889
2890 if ( !stream.IsSeekable() )
2891 return false; // can't test unseekable stream
2892
2893 wxFileOffset posOld = stream.TellI();
2894 bool ok = DoCanRead(stream);
2895
2896 // restore the old position to be able to test other formats and so on
2897 if ( stream.SeekI(posOld) == wxInvalidOffset )
2898 {
2899 wxLogDebug(wxT("Failed to rewind the stream in wxImageHandler!"));
2900
2901 // reading would fail anyhow as we're not at the right position
2902 return false;
2903 }
2904
2905 return ok;
2906 }
2907
2908 #endif // wxUSE_STREAMS
2909
2910 /* static */
2911 wxImageResolution
2912 wxImageHandler::GetResolutionFromOptions(const wxImage& image, int *x, int *y)
2913 {
2914 wxCHECK_MSG( x && y, wxIMAGE_RESOLUTION_NONE, wxT("NULL pointer") );
2915
2916 if ( image.HasOption(wxIMAGE_OPTION_RESOLUTIONX) &&
2917 image.HasOption(wxIMAGE_OPTION_RESOLUTIONY) )
2918 {
2919 *x = image.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONX);
2920 *y = image.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONY);
2921 }
2922 else if ( image.HasOption(wxIMAGE_OPTION_RESOLUTION) )
2923 {
2924 *x =
2925 *y = image.GetOptionInt(wxIMAGE_OPTION_RESOLUTION);
2926 }
2927 else // no resolution options specified
2928 {
2929 *x =
2930 *y = 0;
2931
2932 return wxIMAGE_RESOLUTION_NONE;
2933 }
2934
2935 // get the resolution unit too
2936 int resUnit = image.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONUNIT);
2937 if ( !resUnit )
2938 {
2939 // this is the default
2940 resUnit = wxIMAGE_RESOLUTION_INCHES;
2941 }
2942
2943 return (wxImageResolution)resUnit;
2944 }
2945
2946 // ----------------------------------------------------------------------------
2947 // image histogram stuff
2948 // ----------------------------------------------------------------------------
2949
2950 bool
2951 wxImageHistogram::FindFirstUnusedColour(unsigned char *r,
2952 unsigned char *g,
2953 unsigned char *b,
2954 unsigned char r2,
2955 unsigned char b2,
2956 unsigned char g2) const
2957 {
2958 unsigned long key = MakeKey(r2, g2, b2);
2959
2960 while ( find(key) != end() )
2961 {
2962 // color already used
2963 r2++;
2964 if ( r2 >= 255 )
2965 {
2966 r2 = 0;
2967 g2++;
2968 if ( g2 >= 255 )
2969 {
2970 g2 = 0;
2971 b2++;
2972 if ( b2 >= 255 )
2973 {
2974 wxLogError(_("No unused colour in image.") );
2975 return false;
2976 }
2977 }
2978 }
2979
2980 key = MakeKey(r2, g2, b2);
2981 }
2982
2983 if ( r )
2984 *r = r2;
2985 if ( g )
2986 *g = g2;
2987 if ( b )
2988 *b = b2;
2989
2990 return true;
2991 }
2992
2993 bool
2994 wxImage::FindFirstUnusedColour(unsigned char *r,
2995 unsigned char *g,
2996 unsigned char *b,
2997 unsigned char r2,
2998 unsigned char b2,
2999 unsigned char g2) const
3000 {
3001 wxImageHistogram histogram;
3002
3003 ComputeHistogram(histogram);
3004
3005 return histogram.FindFirstUnusedColour(r, g, b, r2, g2, b2);
3006 }
3007
3008
3009
3010 // GRG, Dic/99
3011 // Counts and returns the number of different colours. Optionally stops
3012 // when it exceeds 'stopafter' different colours. This is useful, for
3013 // example, to see if the image can be saved as 8-bit (256 colour or
3014 // less, in this case it would be invoked as CountColours(256)). Default
3015 // value for stopafter is -1 (don't care).
3016 //
3017 unsigned long wxImage::CountColours( unsigned long stopafter ) const
3018 {
3019 wxHashTable h;
3020 wxObject dummy;
3021 unsigned char r, g, b;
3022 unsigned char *p;
3023 unsigned long size, nentries, key;
3024
3025 p = GetData();
3026 size = GetWidth() * GetHeight();
3027 nentries = 0;
3028
3029 for (unsigned long j = 0; (j < size) && (nentries <= stopafter) ; j++)
3030 {
3031 r = *(p++);
3032 g = *(p++);
3033 b = *(p++);
3034 key = wxImageHistogram::MakeKey(r, g, b);
3035
3036 if (h.Get(key) == NULL)
3037 {
3038 h.Put(key, &dummy);
3039 nentries++;
3040 }
3041 }
3042
3043 return nentries;
3044 }
3045
3046
3047 unsigned long wxImage::ComputeHistogram( wxImageHistogram &h ) const
3048 {
3049 unsigned char *p = GetData();
3050 unsigned long nentries = 0;
3051
3052 h.clear();
3053
3054 const unsigned long size = GetWidth() * GetHeight();
3055
3056 unsigned char r, g, b;
3057 for ( unsigned long n = 0; n < size; n++ )
3058 {
3059 r = *p++;
3060 g = *p++;
3061 b = *p++;
3062
3063 wxImageHistogramEntry& entry = h[wxImageHistogram::MakeKey(r, g, b)];
3064
3065 if ( entry.value++ == 0 )
3066 entry.index = nentries++;
3067 }
3068
3069 return nentries;
3070 }
3071
3072 /*
3073 * Rotation code by Carlos Moreno
3074 */
3075
3076 static const double wxROTATE_EPSILON = 1e-10;
3077
3078 // Auxiliary function to rotate a point (x,y) with respect to point p0
3079 // make it inline and use a straight return to facilitate optimization
3080 // also, the function receives the sine and cosine of the angle to avoid
3081 // repeating the time-consuming calls to these functions -- sin/cos can
3082 // be computed and stored in the calling function.
3083
3084 static inline wxRealPoint
3085 wxRotatePoint(const wxRealPoint& p, double cos_angle, double sin_angle,
3086 const wxRealPoint& p0)
3087 {
3088 return wxRealPoint(p0.x + (p.x - p0.x) * cos_angle - (p.y - p0.y) * sin_angle,
3089 p0.y + (p.y - p0.y) * cos_angle + (p.x - p0.x) * sin_angle);
3090 }
3091
3092 static inline wxRealPoint
3093 wxRotatePoint(double x, double y, double cos_angle, double sin_angle,
3094 const wxRealPoint & p0)
3095 {
3096 return wxRotatePoint (wxRealPoint(x,y), cos_angle, sin_angle, p0);
3097 }
3098
3099 wxImage wxImage::Rotate(double angle,
3100 const wxPoint& centre_of_rotation,
3101 bool interpolating,
3102 wxPoint *offset_after_rotation) const
3103 {
3104 // screen coordinates are a mirror image of "real" coordinates
3105 angle = -angle;
3106
3107 const bool has_alpha = HasAlpha();
3108
3109 const int w = GetWidth();
3110 const int h = GetHeight();
3111
3112 int i;
3113
3114 // Create pointer-based array to accelerate access to wxImage's data
3115 unsigned char ** data = new unsigned char * [h];
3116 data[0] = GetData();
3117 for (i = 1; i < h; i++)
3118 data[i] = data[i - 1] + (3 * w);
3119
3120 // Same for alpha channel
3121 unsigned char ** alpha = NULL;
3122 if (has_alpha)
3123 {
3124 alpha = new unsigned char * [h];
3125 alpha[0] = GetAlpha();
3126 for (i = 1; i < h; i++)
3127 alpha[i] = alpha[i - 1] + w;
3128 }
3129
3130 // precompute coefficients for rotation formula
3131 const double cos_angle = cos(angle);
3132 const double sin_angle = sin(angle);
3133
3134 // Create new Image to store the result
3135 // First, find rectangle that covers the rotated image; to do that,
3136 // rotate the four corners
3137
3138 const wxRealPoint p0(centre_of_rotation.x, centre_of_rotation.y);
3139
3140 wxRealPoint p1 = wxRotatePoint (0, 0, cos_angle, sin_angle, p0);
3141 wxRealPoint p2 = wxRotatePoint (0, h, cos_angle, sin_angle, p0);
3142 wxRealPoint p3 = wxRotatePoint (w, 0, cos_angle, sin_angle, p0);
3143 wxRealPoint p4 = wxRotatePoint (w, h, cos_angle, sin_angle, p0);
3144
3145 int x1a = (int) floor (wxMin (wxMin(p1.x, p2.x), wxMin(p3.x, p4.x)));
3146 int y1a = (int) floor (wxMin (wxMin(p1.y, p2.y), wxMin(p3.y, p4.y)));
3147 int x2a = (int) ceil (wxMax (wxMax(p1.x, p2.x), wxMax(p3.x, p4.x)));
3148 int y2a = (int) ceil (wxMax (wxMax(p1.y, p2.y), wxMax(p3.y, p4.y)));
3149
3150 // Create rotated image
3151 wxImage rotated (x2a - x1a + 1, y2a - y1a + 1, false);
3152 // With alpha channel
3153 if (has_alpha)
3154 rotated.SetAlpha();
3155
3156 if (offset_after_rotation != NULL)
3157 {
3158 *offset_after_rotation = wxPoint (x1a, y1a);
3159 }
3160
3161 // the rotated (destination) image is always accessed sequentially via this
3162 // pointer, there is no need for pointer-based arrays here
3163 unsigned char *dst = rotated.GetData();
3164
3165 unsigned char *alpha_dst = has_alpha ? rotated.GetAlpha() : NULL;
3166
3167 // if the original image has a mask, use its RGB values as the blank pixel,
3168 // else, fall back to default (black).
3169 unsigned char blank_r = 0;
3170 unsigned char blank_g = 0;
3171 unsigned char blank_b = 0;
3172
3173 if (HasMask())
3174 {
3175 blank_r = GetMaskRed();
3176 blank_g = GetMaskGreen();
3177 blank_b = GetMaskBlue();
3178 rotated.SetMaskColour( blank_r, blank_g, blank_b );
3179 }
3180
3181 // Now, for each point of the rotated image, find where it came from, by
3182 // performing an inverse rotation (a rotation of -angle) and getting the
3183 // pixel at those coordinates
3184
3185 const int rH = rotated.GetHeight();
3186 const int rW = rotated.GetWidth();
3187
3188 // do the (interpolating) test outside of the loops, so that it is done
3189 // only once, instead of repeating it for each pixel.
3190 if (interpolating)
3191 {
3192 for (int y = 0; y < rH; y++)
3193 {
3194 for (int x = 0; x < rW; x++)
3195 {
3196 wxRealPoint src = wxRotatePoint (x + x1a, y + y1a, cos_angle, -sin_angle, p0);
3197
3198 if (-0.25 < src.x && src.x < w - 0.75 &&
3199 -0.25 < src.y && src.y < h - 0.75)
3200 {
3201 // interpolate using the 4 enclosing grid-points. Those
3202 // points can be obtained using floor and ceiling of the
3203 // exact coordinates of the point
3204 int x1, y1, x2, y2;
3205
3206 if (0 < src.x && src.x < w - 1)
3207 {
3208 x1 = wxRound(floor(src.x));
3209 x2 = wxRound(ceil(src.x));
3210 }
3211 else // else means that x is near one of the borders (0 or width-1)
3212 {
3213 x1 = x2 = wxRound (src.x);
3214 }
3215
3216 if (0 < src.y && src.y < h - 1)
3217 {
3218 y1 = wxRound(floor(src.y));
3219 y2 = wxRound(ceil(src.y));
3220 }
3221 else
3222 {
3223 y1 = y2 = wxRound (src.y);
3224 }
3225
3226 // get four points and the distances (square of the distance,
3227 // for efficiency reasons) for the interpolation formula
3228
3229 // GRG: Do not calculate the points until they are
3230 // really needed -- this way we can calculate
3231 // just one, instead of four, if d1, d2, d3
3232 // or d4 are < wxROTATE_EPSILON
3233
3234 const double d1 = (src.x - x1) * (src.x - x1) + (src.y - y1) * (src.y - y1);
3235 const double d2 = (src.x - x2) * (src.x - x2) + (src.y - y1) * (src.y - y1);
3236 const double d3 = (src.x - x2) * (src.x - x2) + (src.y - y2) * (src.y - y2);
3237 const double d4 = (src.x - x1) * (src.x - x1) + (src.y - y2) * (src.y - y2);
3238
3239 // Now interpolate as a weighted average of the four surrounding
3240 // points, where the weights are the distances to each of those points
3241
3242 // If the point is exactly at one point of the grid of the source
3243 // image, then don't interpolate -- just assign the pixel
3244
3245 // d1,d2,d3,d4 are positive -- no need for abs()
3246 if (d1 < wxROTATE_EPSILON)
3247 {
3248 unsigned char *p = data[y1] + (3 * x1);
3249 *(dst++) = *(p++);
3250 *(dst++) = *(p++);
3251 *(dst++) = *p;
3252
3253 if (has_alpha)
3254 *(alpha_dst++) = *(alpha[y1] + x1);
3255 }
3256 else if (d2 < wxROTATE_EPSILON)
3257 {
3258 unsigned char *p = data[y1] + (3 * x2);
3259 *(dst++) = *(p++);
3260 *(dst++) = *(p++);
3261 *(dst++) = *p;
3262
3263 if (has_alpha)
3264 *(alpha_dst++) = *(alpha[y1] + x2);
3265 }
3266 else if (d3 < wxROTATE_EPSILON)
3267 {
3268 unsigned char *p = data[y2] + (3 * x2);
3269 *(dst++) = *(p++);
3270 *(dst++) = *(p++);
3271 *(dst++) = *p;
3272
3273 if (has_alpha)
3274 *(alpha_dst++) = *(alpha[y2] + x2);
3275 }
3276 else if (d4 < wxROTATE_EPSILON)
3277 {
3278 unsigned char *p = data[y2] + (3 * x1);
3279 *(dst++) = *(p++);
3280 *(dst++) = *(p++);
3281 *(dst++) = *p;
3282
3283 if (has_alpha)
3284 *(alpha_dst++) = *(alpha[y2] + x1);
3285 }
3286 else
3287 {
3288 // weights for the weighted average are proportional to the inverse of the distance
3289 unsigned char *v1 = data[y1] + (3 * x1);
3290 unsigned char *v2 = data[y1] + (3 * x2);
3291 unsigned char *v3 = data[y2] + (3 * x2);
3292 unsigned char *v4 = data[y2] + (3 * x1);
3293
3294 const double w1 = 1/d1, w2 = 1/d2, w3 = 1/d3, w4 = 1/d4;
3295
3296 // GRG: Unrolled.
3297
3298 *(dst++) = (unsigned char)
3299 ( (w1 * *(v1++) + w2 * *(v2++) +
3300 w3 * *(v3++) + w4 * *(v4++)) /
3301 (w1 + w2 + w3 + w4) );
3302 *(dst++) = (unsigned char)
3303 ( (w1 * *(v1++) + w2 * *(v2++) +
3304 w3 * *(v3++) + w4 * *(v4++)) /
3305 (w1 + w2 + w3 + w4) );
3306 *(dst++) = (unsigned char)
3307 ( (w1 * *v1 + w2 * *v2 +
3308 w3 * *v3 + w4 * *v4) /
3309 (w1 + w2 + w3 + w4) );
3310
3311 if (has_alpha)
3312 {
3313 v1 = alpha[y1] + (x1);
3314 v2 = alpha[y1] + (x2);
3315 v3 = alpha[y2] + (x2);
3316 v4 = alpha[y2] + (x1);
3317
3318 *(alpha_dst++) = (unsigned char)
3319 ( (w1 * *v1 + w2 * *v2 +
3320 w3 * *v3 + w4 * *v4) /
3321 (w1 + w2 + w3 + w4) );
3322 }
3323 }
3324 }
3325 else
3326 {
3327 *(dst++) = blank_r;
3328 *(dst++) = blank_g;
3329 *(dst++) = blank_b;
3330
3331 if (has_alpha)
3332 *(alpha_dst++) = 0;
3333 }
3334 }
3335 }
3336 }
3337 else // not interpolating
3338 {
3339 for (int y = 0; y < rH; y++)
3340 {
3341 for (int x = 0; x < rW; x++)
3342 {
3343 wxRealPoint src = wxRotatePoint (x + x1a, y + y1a, cos_angle, -sin_angle, p0);
3344
3345 const int xs = wxRound (src.x); // wxRound rounds to the
3346 const int ys = wxRound (src.y); // closest integer
3347
3348 if (0 <= xs && xs < w && 0 <= ys && ys < h)
3349 {
3350 unsigned char *p = data[ys] + (3 * xs);
3351 *(dst++) = *(p++);
3352 *(dst++) = *(p++);
3353 *(dst++) = *p;
3354
3355 if (has_alpha)
3356 *(alpha_dst++) = *(alpha[ys] + (xs));
3357 }
3358 else
3359 {
3360 *(dst++) = blank_r;
3361 *(dst++) = blank_g;
3362 *(dst++) = blank_b;
3363
3364 if (has_alpha)
3365 *(alpha_dst++) = 255;
3366 }
3367 }
3368 }
3369 }
3370
3371 delete [] data;
3372 delete [] alpha;
3373
3374 return rotated;
3375 }
3376
3377
3378
3379
3380
3381 // A module to allow wxImage initialization/cleanup
3382 // without calling these functions from app.cpp or from
3383 // the user's application.
3384
3385 class wxImageModule: public wxModule
3386 {
3387 DECLARE_DYNAMIC_CLASS(wxImageModule)
3388 public:
3389 wxImageModule() {}
3390 bool OnInit() { wxImage::InitStandardHandlers(); return true; }
3391 void OnExit() { wxImage::CleanUpHandlers(); }
3392 };
3393
3394 IMPLEMENT_DYNAMIC_CLASS(wxImageModule, wxModule)
3395
3396
3397 #endif // wxUSE_IMAGE