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