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