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