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