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