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