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