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