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