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