]> git.saurik.com Git - wxWidgets.git/blob - wxPython/src/_image.i
Premultiply the alpha on wxMSW in the BitmapFromBuffer* functions so
[wxWidgets.git] / wxPython / src / _image.i
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: _image.i
3 // Purpose: SWIG definitions for wxImage and such
4 //
5 // Author: Robin Dunn
6 //
7 // Created: 25-Sept-2000
8 // RCS-ID: $Id$
9 // Copyright: (c) 2003 by Total Control Software
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
12
13 // Not a %module
14
15
16 //---------------------------------------------------------------------------
17
18 %{
19 #include "wx/wxPython/pyistream.h"
20 %}
21
22 //---------------------------------------------------------------------------
23
24 enum {
25 wxIMAGE_ALPHA_TRANSPARENT,
26 wxIMAGE_ALPHA_THRESHOLD,
27 wxIMAGE_ALPHA_OPAQUE
28 };
29
30
31 //---------------------------------------------------------------------------
32 %newgroup
33
34 DocStr(wxImageHandler,
35 "This is the base class for implementing image file loading/saving, and
36 image creation from data. It is used within `wx.Image` and is not
37 normally seen by the application.", "");
38 class wxImageHandler : public wxObject {
39 public:
40 // wxImageHandler(); Abstract Base Class
41 wxString GetName();
42 wxString GetExtension();
43 long GetType();
44 wxString GetMimeType();
45
46 //bool LoadFile(wxImage* image, wxInputStream& stream);
47 //bool SaveFile(wxImage* image, wxOutputStream& stream);
48 //virtual int GetImageCount( wxInputStream& stream );
49
50 bool CanRead( const wxString& name );
51 %Rename(CanReadStream, bool, CanRead( wxInputStream& stream ));
52
53 void SetName(const wxString& name);
54 void SetExtension(const wxString& extension);
55 void SetType(long type);
56 void SetMimeType(const wxString& mimetype);
57 };
58
59
60 //---------------------------------------------------------------------------
61
62
63 DocStr(wxPyImageHandler,
64 "This is the base class for implementing image file loading/saving, and
65 image creation from data, all written in Python. To create a custom
66 image handler derive a new class from wx.PyImageHandler and provide
67 the following methods::
68
69 def DoCanRead(self, stream) --> bool
70 '''Check if this handler can read the image on the stream'''
71
72 def LoadFile(self, image, stream, verbose, index) --> bool
73 '''Load image data from the stream and load it into image.'''
74
75 def SaveFile(self, image, stream, verbose) --> bool
76 '''Save the iamge data in image to the stream using
77 this handler's image file format.'''
78
79 def GetImageCount(self, stream) --> int
80 '''If this image format can hold more than one image,
81 how many does the image on the stream have?'''
82
83 To activate your handler create an instance of it and pass it to
84 `wx.Image_AddHandler`. Be sure to call `SetName`, `SetType`, and
85 `SetExtension` from your constructor.
86 ", "");
87
88 class wxPyImageHandler: public wxImageHandler {
89 public:
90 %pythonAppend wxPyImageHandler() "self._SetSelf(self)"
91 wxPyImageHandler();
92 void _SetSelf(PyObject *self);
93 };
94
95
96 //---------------------------------------------------------------------------
97
98
99 class wxImageHistogram /* : public wxImageHistogramBase */
100 {
101 public:
102 wxImageHistogram();
103
104 DocStr(MakeKey, "Get the key in the histogram for the given RGB values", "");
105 static unsigned long MakeKey(byte r,
106 byte g,
107 byte b);
108
109 DocDeclAStr(
110 bool, FindFirstUnusedColour(byte *OUTPUT,
111 byte *OUTPUT,
112 byte *OUTPUT,
113 byte startR = 1,
114 byte startG = 0,
115 byte startB = 0 ) const,
116 "FindFirstUnusedColour(int startR=1, int startG=0, int startB=0) -> (success, r, g, b)",
117 "Find first colour that is not used in the image and has higher RGB
118 values than startR, startG, startB. Returns a tuple consisting of a
119 success flag and rgb values.", "");
120
121 %extend {
122 DocStr(GetCount,
123 "Returns the pixel count for the given key. Use `MakeKey` to create a
124 key value from a RGB tripple.", "");
125 unsigned long GetCount(unsigned long key) {
126 wxImageHistogramEntry e = (*self)[key];
127 return e.value;
128 }
129
130 DocStr(GetCountRGB,
131 "Returns the pixel count for the given RGB values.", "");
132 unsigned long GetCountRGB(byte r,
133 byte g,
134 byte b) {
135 unsigned long key = wxImageHistogram::MakeKey(r, g, b);
136 wxImageHistogramEntry e = (*self)[key];
137 return e.value;
138 }
139
140 DocStr(GetCountColour,
141 "Returns the pixel count for the given `wx.Colour` value.", "");
142 unsigned long GetCountColour(const wxColour& colour) {
143 unsigned long key = wxImageHistogram::MakeKey(colour.Red(),
144 colour.Green(),
145 colour.Blue());
146 wxImageHistogramEntry e = (*self)[key];
147 return e.value;
148 }
149 }
150
151 };
152
153
154 //---------------------------------------------------------------------------
155
156 DocStr(wxImage,
157 "A platform-independent image class. An image can be created from
158 data, or using `wx.Bitmap.ConvertToImage`, or loaded from a file in a
159 variety of formats. Functions are available to set and get image
160 bits, so it can be used for basic image manipulation.
161
162 A wx.Image cannot be drawn directly to a `wx.DC`. Instead, a
163 platform-specific `wx.Bitmap` object must be created from it using the
164 `wx.BitmapFromImage` constructor. This bitmap can then be drawn in a
165 device context, using `wx.DC.DrawBitmap`.
166
167 One colour value of the image may be used as a mask colour which will
168 lead to the automatic creation of a `wx.Mask` object associated to the
169 bitmap object.
170
171 wx.Image supports alpha channel data, that is in addition to a byte
172 for the red, green and blue colour components for each pixel it also
173 stores a byte representing the pixel opacity. An alpha value of 0
174 corresponds to a transparent pixel (null opacity) while a value of 255
175 means that the pixel is 100% opaque.
176
177 Unlike RGB data, not all images have an alpha channel and before using
178 `GetAlpha` you should check if this image contains an alpha channel
179 with `HasAlpha`. Note that currently only images loaded from PNG files
180 with transparency information will have an alpha channel.", "");
181
182
183 %{
184 // Pull the nested class out to the top level for SWIG's sake
185 #define wxImage_RGBValue wxImage::RGBValue
186 #define wxImage_HSVValue wxImage::HSVValue
187 %}
188
189 DocStr(wxImage_RGBValue,
190 "An object that contains values for red, green and blue which represent
191 the value of a color. It is used by `wx.Image.HSVtoRGB` and
192 `wx.Image.RGBtoHSV`, which converts between HSV color space and RGB
193 color space.", "");
194 class wxImage_RGBValue
195 {
196 public:
197 DocCtorStr(
198 wxImage_RGBValue(byte r=0, byte g=0, byte b=0),
199 "Constructor.", "");
200 byte red;
201 byte green;
202 byte blue;
203 };
204
205
206 DocStr(wxImage_HSVValue,
207 "An object that contains values for hue, saturation and value which
208 represent the value of a color. It is used by `wx.Image.HSVtoRGB` and
209 `wx.Image.RGBtoHSV`, which +converts between HSV color space and RGB
210 color space.", "");
211 class wxImage_HSVValue
212 {
213 public:
214 DocCtorStr(
215 wxImage_HSVValue(double h=0.0, double s=0.0, double v=0.0),
216 "Constructor.", "");
217 double hue;
218 double saturation;
219 double value;
220 };
221
222
223 class wxImage : public wxObject {
224 public:
225 %typemap(out) wxImage*; // turn off this typemap
226
227 DocCtorStr(
228 wxImage( const wxString& name, long type = wxBITMAP_TYPE_ANY, int index = -1 ),
229 "Loads an image from a file.",
230 "
231 :param name: Name of the file from which to load the image.
232
233 :param type: May be one of the following:
234
235 ==================== =======================================
236 wx.BITMAP_TYPE_BMP Load a Windows bitmap file.
237 wx.BITMAP_TYPE_GIF Load a GIF bitmap file.
238 wx.BITMAP_TYPE_JPEG Load a JPEG bitmap file.
239 wx.BITMAP_TYPE_PNG Load a PNG bitmap file.
240 wx.BITMAP_TYPE_PCX Load a PCX bitmap file.
241 wx.BITMAP_TYPE_PNM Load a PNM bitmap file.
242 wx.BITMAP_TYPE_TIF Load a TIFF bitmap file.
243 wx.BITMAP_TYPE_XPM Load a XPM bitmap file.
244 wx.BITMAP_TYPE_ICO Load a Windows icon file (ICO).
245 wx.BITMAP_TYPE_CUR Load a Windows cursor file (CUR).
246 wx.BITMAP_TYPE_ANI Load a Windows animated cursor file (ANI).
247 wx.BITMAP_TYPE_ANY Will try to autodetect the format.
248 ==================== =======================================
249
250 :param index: Index of the image to load in the case that the
251 image file contains multiple images. This is only used by GIF,
252 ICO and TIFF handlers. The default value (-1) means to choose
253 the default image and is interpreted as the first image (the
254 one with index=0) by the GIF and TIFF handler and as the
255 largest and most colourful one by the ICO handler.
256
257 :see: `wx.ImageFromMime`, `wx.ImageFromStream`, `wx.ImageFromStreamMime`,
258 `wx.EmptyImage`, `wx.ImageFromBitmap`, `wx.ImageFromBuffer`,
259 `wx.ImageFromData`, `wx.ImageFromDataWithAlpha`
260 ");
261
262 ~wxImage();
263
264 // Alternate constructors
265 DocCtorStrName(
266 wxImage(const wxString& name, const wxString& mimetype, int index = -1),
267 "Loads an image from a file, using a MIME type string (such as
268 'image/jpeg') to specify image type.", "
269
270 :see: `wx.Image`",
271 ImageFromMime);
272
273 DocCtorStrName(
274 wxImage(wxInputStream& stream, long type = wxBITMAP_TYPE_ANY, int index = -1),
275 "Loads an image from an input stream, or any readable Python file-like
276 object.", "
277
278 :see: `wx.Image`",
279 ImageFromStream);
280
281 DocCtorStrName(
282 wxImage(wxInputStream& stream, const wxString& mimetype, int index = -1 ),
283 "Loads an image from an input stream, or any readable Python file-like
284 object, specifying the image format with a MIME type string.", "
285
286 :see: `wx.Image`",
287 ImageFromStreamMime);
288
289 %extend {
290 %RenameDocCtor(
291 EmptyImage,
292 "Construct an empty image of a given size, optionally setting all
293 pixels to black.", "
294
295 :see: `wx.Image`",
296 wxImage(int width=0, int height=0, bool clear = true))
297 {
298 if (width > 0 && height > 0)
299 return new wxImage(width, height, clear);
300 else
301 return new wxImage;
302 }
303
304
305 MustHaveApp(wxImage(const wxBitmap &bitmap));
306
307 %RenameDocCtor(
308 ImageFromBitmap,
309 "Construct an Image from a `wx.Bitmap`.", "
310
311 :see: `wx.Image`",
312 wxImage(const wxBitmap &bitmap))
313 {
314 return new wxImage(bitmap.ConvertToImage());
315 }
316
317 %RenameDocCtor(
318 ImageFromData,
319 "Construct an Image from a buffer of RGB bytes. Accepts either a
320 string or a buffer object holding the data and the length of the data
321 must be width*height*3.", "
322
323 :see: `wx.Image`",
324 wxImage(int width, int height, buffer data, int DATASIZE))
325 {
326 if (DATASIZE != width*height*3) {
327 wxPyErr_SetString(PyExc_ValueError, "Invalid data buffer size.");
328 return NULL;
329 }
330
331 // Copy the source data so the wxImage can clean it up later
332 buffer copy = (buffer)malloc(DATASIZE);
333 if (copy == NULL) {
334 wxPyBLOCK_THREADS(PyErr_NoMemory());
335 return NULL;
336 }
337 memcpy(copy, data, DATASIZE);
338 return new wxImage(width, height, copy, false);
339 }
340
341
342 %RenameDocCtor(
343 ImageFromDataWithAlpha,
344 "Construct an Image from a buffer of RGB bytes with an Alpha channel.
345 Accepts either a string or a buffer object holding the data and the
346 length of the data must be width*height*3 bytes, and the length of the
347 alpha data must be width*height bytes.", "
348
349 :see: `wx.Image`",
350 wxImage(int width, int height, buffer data, int DATASIZE, buffer alpha, int ALPHASIZE))
351 {
352 if (DATASIZE != width*height*3) {
353 wxPyErr_SetString(PyExc_ValueError, "Invalid data buffer size.");
354 return NULL;
355 }
356 if (ALPHASIZE != width*height) {
357 wxPyErr_SetString(PyExc_ValueError, "Invalid alpha buffer size.");
358 return NULL;
359 }
360
361 // Copy the source data so the wxImage can clean it up later
362 buffer dcopy = (buffer)malloc(DATASIZE);
363 if (dcopy == NULL) {
364 wxPyBLOCK_THREADS(PyErr_NoMemory());
365 return NULL;
366 }
367 memcpy(dcopy, data, DATASIZE);
368
369 buffer acopy = (buffer)malloc(ALPHASIZE);
370 if (acopy == NULL) {
371 wxPyBLOCK_THREADS(PyErr_NoMemory());
372 return NULL;
373 }
374 memcpy(acopy, alpha, ALPHASIZE);
375
376 return new wxImage(width, height, dcopy, acopy, false);
377 }
378 }
379
380 // TODO: wxImage( char** xpmData );
381
382 // Turn the typemap back on again
383 %typemap(out) wxImage* { $result = wxPyMake_wxObject($1, $owner); }
384
385
386 DocDeclStr(
387 void , Create( int width, int height, bool clear=true ),
388 "Creates a fresh image. If clear is ``True``, the new image will be
389 initialized to black. Otherwise, the image data will be uninitialized.", "");
390
391 DocDeclStr(
392 void , Destroy(),
393 "Destroys the image data.", "");
394
395
396 DocDeclStr(
397 wxImage , Scale( int width, int height ),
398 "Returns a scaled version of the image. This is also useful for scaling
399 bitmaps in general as the only other way to scale bitmaps is to blit a
400 `wx.MemoryDC` into another `wx.MemoryDC`.", "
401
402 :see: `Rescale`");
403
404 DocDeclStr(
405 wxImage , ShrinkBy( int xFactor , int yFactor ) const ,
406 "Return a version of the image scaled smaller by the given factors.", "");
407
408 DocDeclStr(
409 wxImage& , Rescale(int width, int height),
410 "Changes the size of the image in-place by scaling it: after a call to
411 this function, the image will have the given width and height.
412
413 Returns the (modified) image itself.", "
414
415 :see: `Scale`");
416
417
418 // resizes the image in place
419 DocDeclStr(
420 wxImage& , Resize( const wxSize& size, const wxPoint& pos,
421 int r = -1, int g = -1, int b = -1 ),
422 "Changes the size of the image in-place without scaling it, by adding
423 either a border with the given colour or cropping as necessary. The
424 image is pasted into a new image with the given size and background
425 colour at the position pos relative to the upper left of the new
426 image. If red = green = blue = -1 then use either the current mask
427 colour if set or find, use, and set a suitable mask colour for any
428 newly exposed areas.
429
430 Returns the (modified) image itself.", "
431
432 :see: `Size`");
433
434
435 DocDeclStr(
436 void , SetRGB( int x, int y, byte r, byte g, byte b ),
437 "Sets the pixel at the given coordinate. This routine performs
438 bounds-checks for the coordinate so it can be considered a safe way to
439 manipulate the data, but in some cases this might be too slow so that
440 the data will have to be set directly. In that case you will have to
441 get access to the image data using the `GetData` method.", "");
442
443
444 DocDeclStrName(
445 void, SetRGB( const wxRect& rect,
446 byte r, byte g, byte b ),
447 "Sets the colour of the pixels within the given rectangle. This routine
448 performs bounds-checks for the rectangle so it can be considered a
449 safe way to manipulate the data.", "",
450 SetRGBRect);
451
452 DocDeclStr(
453 byte , GetRed( int x, int y ),
454 "Returns the red intensity at the given coordinate.", "");
455
456 DocDeclStr(
457 byte , GetGreen( int x, int y ),
458 "Returns the green intensity at the given coordinate.", "");
459
460 DocDeclStr(
461 byte , GetBlue( int x, int y ),
462 "Returns the blue intensity at the given coordinate.", "");
463
464
465 DocDeclStr(
466 void , SetAlpha(int x, int y, byte alpha),
467 "Sets the alpha value for the given pixel. This function should only be
468 called if the image has alpha channel data, use `HasAlpha` to check
469 for this.", "");
470
471 DocDeclStr(
472 byte , GetAlpha(int x, int y),
473 "Returns the alpha value for the given pixel. This function may only be
474 called for the images with alpha channel, use `HasAlpha` to check for
475 this.
476
477 The returned value is the *opacity* of the image, i.e. the value of 0
478 corresponds to the fully transparent pixels while the value of 255 to
479 the fully opaque pixels.", "");
480
481 DocDeclStr(
482 bool , HasAlpha(),
483 "Returns true if this image has alpha channel, false otherwise.", "
484
485 :see: `GetAlpha`, `SetAlpha`");
486
487
488 DocDeclStr(
489 void , InitAlpha(),
490 "Initializes the image alpha channel data. It is an error to call it if
491 the image already has alpha data. If it doesn't, alpha data will be by
492 default initialized to all pixels being fully opaque. But if the image
493 has a a mask colour, all mask pixels will be completely transparent.", "");
494
495
496 DocDeclStr(
497 bool , IsTransparent(int x, int y,
498 byte threshold = wxIMAGE_ALPHA_THRESHOLD) const,
499 "Returns ``True`` if this pixel is masked or has an alpha value less
500 than the spcified threshold.", "");
501
502
503 // find first colour that is not used in the image and has higher
504 // RGB values than <startR,startG,startB>
505 DocDeclAStr(
506 bool, FindFirstUnusedColour( byte *OUTPUT, byte *OUTPUT, byte *OUTPUT,
507 byte startR = 0, byte startG = 0, byte startB = 0 ) const,
508 "FindFirstUnusedColour(int startR=1, int startG=0, int startB=0) -> (success, r, g, b)",
509 "Find first colour that is not used in the image and has higher RGB
510 values than startR, startG, startB. Returns a tuple consisting of a
511 success flag and rgb values.", "");
512
513
514 DocDeclStr(
515 bool , ConvertAlphaToMask(byte threshold = wxIMAGE_ALPHA_THRESHOLD),
516 "If the image has alpha channel, this method converts it to mask. All
517 pixels with alpha value less than ``threshold`` are replaced with the
518 mask colour and the alpha channel is removed. The mask colour is
519 chosen automatically using `FindFirstUnusedColour`.
520
521 If the image image doesn't have alpha channel, ConvertAlphaToMask does
522 nothing.", "");
523
524
525 DocDeclStr(
526 bool , ConvertColourToAlpha( byte r, byte g, byte b ),
527 "This method converts an image where the original alpha information is
528 only available as a shades of a colour (actually shades of grey)
529 typically when you draw anti-aliased text into a bitmap. The DC
530 drawing routines draw grey values on the black background although
531 they actually mean to draw white with differnt alpha values. This
532 method reverses it, assuming a black (!) background and white text.
533 The method will then fill up the whole image with the colour given.", "");
534
535
536
537 DocDeclStr(
538 bool , SetMaskFromImage(const wxImage & mask,
539 byte mr, byte mg, byte mb),
540 "Sets the image's mask so that the pixels that have RGB value of
541 ``(mr,mg,mb)`` in ``mask`` will be masked in this image. This is done
542 by first finding an unused colour in the image, setting this colour as
543 the mask colour and then using this colour to draw all pixels in the
544 image who corresponding pixel in mask has given RGB value.
545
546 Returns ``False`` if ``mask`` does not have same dimensions as the
547 image or if there is no unused colour left. Returns ``True`` if the
548 mask was successfully applied.
549
550 Note that this method involves computing the histogram, which is
551 computationally intensive operation.", "");
552
553
554 // void DoFloodFill (wxCoord x, wxCoord y,
555 // const wxBrush & fillBrush,
556 // const wxColour& testColour,
557 // int style = wxFLOOD_SURFACE,
558 // int LogicalFunction = wxCOPY /* currently unused */ ) ;
559
560 DocDeclStr(
561 static bool , CanRead( const wxString& filename ),
562 "Returns True if the image handlers can read this file.", "");
563
564 DocDeclStr(
565 static int , GetImageCount( const wxString& filename, long type = wxBITMAP_TYPE_ANY ),
566 "If the image file contains more than one image and the image handler
567 is capable of retrieving these individually, this function will return
568 the number of available images.", "");
569
570
571 DocDeclStr(
572 bool , LoadFile( const wxString& name, long type = wxBITMAP_TYPE_ANY, int index = -1 ),
573 "Loads an image from a file. If no handler type is provided, the
574 library will try to autodetect the format.", "");
575
576 DocDeclStrName(
577 bool , LoadFile( const wxString& name, const wxString& mimetype, int index = -1 ),
578 "Loads an image from a file, specifying the image type with a MIME type
579 string.", "",
580 LoadMimeFile);
581
582
583 DocDeclStr(
584 bool , SaveFile( const wxString& name, int type ),
585 "Saves an image in the named file.", "");
586
587
588 DocDeclStrName(
589 bool , SaveFile( const wxString& name, const wxString& mimetype ),
590 "Saves an image in the named file.", "",
591 SaveMimeFile);
592
593
594 DocDeclStrName(
595 static bool , CanRead( wxInputStream& stream ),
596 "Returns True if the image handlers can read an image file from the
597 data currently on the input stream, or a readable Python file-like
598 object.", "",
599 CanReadStream);
600
601
602 DocDeclStrName(
603 bool , LoadFile( wxInputStream& stream, long type = wxBITMAP_TYPE_ANY, int index = -1 ),
604 "Loads an image from an input stream or a readable Python file-like
605 object. If no handler type is provided, the library will try to
606 autodetect the format.", "",
607 LoadStream);
608
609
610 DocDeclStrName(
611 bool , LoadFile( wxInputStream& stream, const wxString& mimetype, int index = -1 ),
612 "Loads an image from an input stream or a readable Python file-like
613 object, using a MIME type string to specify the image file format.", "",
614 LoadMimeStream);
615
616
617 DocDeclStr(
618 bool , Ok(),
619 "Returns true if image data is present.", "");
620
621 DocDeclStr(
622 int , GetWidth(),
623 "Gets the width of the image in pixels.", "");
624
625 DocDeclStr(
626 int , GetHeight(),
627 "Gets the height of the image in pixels.", "");
628
629
630 %extend {
631 DocStr(GetSize,
632 "Returns the size of the image in pixels.", "");
633 wxSize GetSize() {
634 wxSize size(self->GetWidth(), self->GetHeight());
635 return size;
636 }
637 }
638
639
640 DocDeclStr(
641 wxImage , GetSubImage(const wxRect& rect),
642 "Returns a sub image of the current one as long as the rect belongs
643 entirely to the image.", "");
644
645
646 DocDeclStr(
647 wxImage , Size( const wxSize& size, const wxPoint& pos,
648 int r = -1, int g = -1, int b = -1 ) const,
649 "Returns a resized version of this image without scaling it by adding
650 either a border with the given colour or cropping as necessary. The
651 image is pasted into a new image with the given size and background
652 colour at the position ``pos`` relative to the upper left of the new
653 image. If red = green = blue = -1 then use either the current mask
654 colour if set or find, use, and set a suitable mask colour for any
655 newly exposed areas.", "
656
657 :see: `Resize`");
658
659
660 DocDeclStr(
661 wxImage , Copy(),
662 "Returns an identical copy of the image.", "");
663
664 DocDeclStr(
665 void , Paste( const wxImage &image, int x, int y ),
666 "Pastes ``image`` into this instance and takes care of the mask colour
667 and any out of bounds problems.", "");
668
669
670 //unsigned char *GetData();
671 //void SetData( unsigned char *data );
672
673 %extend {
674 DocStr(GetData,
675 "Returns a string containing a copy of the RGB bytes of the image.", "");
676 PyObject* GetData()
677 {
678 buffer data = self->GetData();
679 int len = self->GetWidth() * self->GetHeight() * 3;
680 PyObject* rv;
681 wxPyBLOCK_THREADS( rv = PyString_FromStringAndSize((char*)data, len));
682 return rv;
683 }
684 DocStr(SetData,
685 "Resets the Image's RGB data from a buffer of RGB bytes. Accepts
686 either a string or a buffer object holding the data and the length of
687 the data must be width*height*3.", "");
688 void SetData(buffer data, int DATASIZE)
689 {
690 if (DATASIZE != self->GetWidth() * self->GetHeight() * 3) {
691 wxPyErr_SetString(PyExc_ValueError, "Invalid data buffer size.");
692 return;
693 }
694 buffer copy = (buffer)malloc(DATASIZE);
695 if (copy == NULL) {
696 wxPyBLOCK_THREADS(PyErr_NoMemory());
697 return;
698 }
699 memcpy(copy, data, DATASIZE);
700 self->SetData(copy, false);
701 // wxImage takes ownership of copy...
702 }
703
704
705 DocStr(GetDataBuffer,
706 "Returns a writable Python buffer object that is pointing at the RGB
707 image data buffer inside the wx.Image. You need to ensure that you do
708 not use this buffer object after the image has been destroyed.", "");
709 PyObject* GetDataBuffer()
710 {
711 buffer data = self->GetData();
712 int len = self->GetWidth() * self->GetHeight() * 3;
713 PyObject* rv;
714 wxPyBLOCK_THREADS( rv = PyBuffer_FromReadWriteMemory(data, len) );
715 return rv;
716 }
717
718 DocStr(SetDataBuffer,
719 "Sets the internal image data pointer to point at a Python buffer
720 object. This can save making an extra copy of the data but you must
721 ensure that the buffer object lives longer than the wx.Image does.", "");
722 void SetDataBuffer(buffer data, int DATASIZE)
723 {
724 if (DATASIZE != self->GetWidth() * self->GetHeight() * 3) {
725 wxPyErr_SetString(PyExc_ValueError, "Invalid data buffer size.");
726 return;
727 }
728 self->SetData(data, true);
729 }
730
731
732
733 DocStr(GetAlphaData,
734 "Returns a string containing a copy of the alpha bytes of the image.", "");
735 PyObject* GetAlphaData() {
736 buffer data = self->GetAlpha();
737 if (! data) {
738 RETURN_NONE();
739 } else {
740 int len = self->GetWidth() * self->GetHeight();
741 PyObject* rv;
742 wxPyBLOCK_THREADS( rv = PyString_FromStringAndSize((char*)data, len) );
743 return rv;
744 }
745 }
746
747 DocStr(SetAlphaData,
748 "Resets the Image's alpha data from a buffer of bytes. Accepts either
749 a string or a buffer object holding the data and the length of the
750 data must be width*height.", "");
751 void SetAlphaData(buffer alpha, int ALPHASIZE)
752 {
753 if (ALPHASIZE != self->GetWidth() * self->GetHeight()) {
754 wxPyErr_SetString(PyExc_ValueError, "Invalid alpha buffer size.");
755 return;
756 }
757 buffer acopy = (buffer)malloc(ALPHASIZE);
758 if (acopy == NULL) {
759 wxPyBLOCK_THREADS(PyErr_NoMemory());
760 return;
761 }
762 memcpy(acopy, alpha, ALPHASIZE);
763 self->SetAlpha(acopy, false);
764 // wxImage takes ownership of acopy...
765 }
766
767
768
769 DocStr(GetAlphaBuffer,
770 "Returns a writable Python buffer object that is pointing at the Alpha
771 data buffer inside the wx.Image. You need to ensure that you do not
772 use this buffer object after the image has been destroyed.", "");
773 PyObject* GetAlphaBuffer()
774 {
775 buffer data = self->GetAlpha();
776 int len = self->GetWidth() * self->GetHeight();
777 PyObject* rv;
778 wxPyBLOCK_THREADS( rv = PyBuffer_FromReadWriteMemory(data, len) );
779 return rv;
780 }
781
782
783 DocStr(SetAlphaBuffer,
784 "Sets the internal image alpha pointer to point at a Python buffer
785 object. This can save making an extra copy of the data but you must
786 ensure that the buffer object lives as long as the wx.Image does.", "");
787 void SetAlphaBuffer(buffer alpha, int ALPHASIZE)
788 {
789 if (ALPHASIZE != self->GetWidth() * self->GetHeight()) {
790 wxPyErr_SetString(PyExc_ValueError, "Invalid alpha buffer size.");
791 return;
792 }
793 self->SetAlpha(alpha, true);
794 }
795 }
796
797
798
799 DocDeclStr(
800 void , SetMaskColour( byte r, byte g, byte b ),
801 "Sets the mask colour for this image (and tells the image to use the
802 mask).", "");
803
804
805 DocDeclAStr(
806 /*bool*/ void , GetOrFindMaskColour( byte *OUTPUT,
807 byte *OUTPUT,
808 byte *OUTPUT ) const,
809 "GetOrFindMaskColour() -> (r,g,b)",
810 "Get the current mask colour or find a suitable colour.", "");
811
812
813 DocDeclStr(
814 byte , GetMaskRed(),
815 "Gets the red component of the mask colour.", "");
816
817 DocDeclStr(
818 byte , GetMaskGreen(),
819 "Gets the green component of the mask colour.", "");
820
821 DocDeclStr(
822 byte , GetMaskBlue(),
823 "Gets the blue component of the mask colour.", "");
824
825 DocDeclStr(
826 void , SetMask( bool mask = true ),
827 "Specifies whether there is a mask or not. The area of the mask is
828 determined by the current mask colour.", "");
829
830 DocDeclStr(
831 bool , HasMask(),
832 "Returns ``True`` if there is a mask active, ``False`` otherwise.", "");
833
834
835 DocDeclStr(
836 wxImage , Rotate(double angle, const wxPoint & centre_of_rotation,
837 bool interpolating = true, wxPoint * offset_after_rotation = NULL) const ,
838 "Rotates the image about the given point, by ``angle`` radians. Passing
839 ``True`` to ``interpolating`` results in better image quality, but is
840 slower. If the image has a mask, then the mask colour is used for the
841 uncovered pixels in the rotated image background. Otherwise, black
842 will be used as the fill colour.
843
844 Returns the rotated image, leaving this image intact.", "");
845
846 DocDeclStr(
847 wxImage , Rotate90( bool clockwise = true ) ,
848 "Returns a copy of the image rotated 90 degrees in the direction
849 indicated by ``clockwise``.", "");
850
851 DocDeclStr(
852 wxImage , Mirror( bool horizontally = true ) ,
853 "Returns a mirrored copy of the image. The parameter ``horizontally``
854 indicates the orientation.", "");
855
856
857 DocDeclStr(
858 void , Replace( byte r1, byte g1, byte b1,
859 byte r2, byte g2, byte b2 ),
860 "Replaces the colour specified by ``(r1,g1,b1)`` by the colour
861 ``(r2,g2,b2)``.", "");
862
863 DocDeclStr(
864 wxImage , ConvertToGreyscale( double lr = 0.299,
865 double lg = 0.587,
866 double lb = 0.114 ) const,
867 "Convert to greyscale image. Uses the luminance component (Y) of the
868 image. The luma value (YUV) is calculated using (R * lr) + (G * lg) + (B * lb),
869 defaults to ITU-T BT.601", "");
870
871
872 DocDeclStr(
873 wxImage , ConvertToMono( byte r, byte g, byte b ) const,
874 "Returns monochromatic version of the image. The returned image has
875 white colour where the original has ``(r,g,b)`` colour and black
876 colour everywhere else.", "");
877
878
879 DocDeclStr(
880 void , SetOption(const wxString& name, const wxString& value),
881 "Sets an image handler defined option. For example, when saving as a
882 JPEG file, the option ``wx.IMAGE_OPTION_QUALITY`` is used, which is a
883 number between 0 and 100 (0 is terrible, 100 is very good).", "
884
885 ================================= ===
886 wx.IMAGE_OPTION_BMP_FORMAT
887 wx.IMAGE_OPTION_CUR_HOTSPOT_X
888 wx.IMAGE_OPTION_CUR_HOTSPOT_Y
889 wx.IMAGE_OPTION_RESOLUTION
890 wx.IMAGE_OPTION_RESOLUTIONX
891 wx.IMAGE_OPTION_RESOLUTIONY
892 wx.IMAGE_OPTION_RESOLUTIONUNIT
893 wx.IMAGE_OPTION_QUALITY
894 wx.IMAGE_OPTION_BITSPERSAMPLE
895 wx.IMAGE_OPTION_SAMPLESPERPIXEL
896 wx.IMAGE_OPTION_COMPRESSION
897 wx.IMAGE_OPTION_IMAGEDESCRIPTOR
898 wx.IMAGE_OPTION_PNG_FORMAT
899 wx.IMAGE_OPTION_PNG_BITDEPTH
900 ================================= ===
901
902 :see: `HasOption`, `GetOption`, `GetOptionInt`, `SetOptionInt`");
903
904 DocDeclStrName(
905 void, SetOption(const wxString& name, int value),
906 "Sets an image option as an integer.", "
907
908 :see: `HasOption`, `GetOption`, `GetOptionInt`, `SetOption`",
909 SetOptionInt);
910
911 DocDeclStr(
912 wxString , GetOption(const wxString& name) const,
913 "Gets the value of an image handler option.", "
914
915 :see: `HasOption`, `GetOptionInt`, `SetOption`, `SetOptionInt`");
916
917 DocDeclStr(
918 int , GetOptionInt(const wxString& name) const,
919 "Gets the value of an image handler option as an integer. If the given
920 option is not present, the function returns 0.", "
921
922 :see: `HasOption`, `GetOption`, `SetOptionInt`, `SetOption`");
923
924 DocDeclStr(
925 bool , HasOption(const wxString& name) const,
926 "Returns true if the given option is present.", "
927
928 :see: `GetOption`, `GetOptionInt`, `SetOption`, `SetOptionInt`");
929
930
931 unsigned long CountColours( unsigned long stopafter = (unsigned long) -1 );
932 unsigned long ComputeHistogram( wxImageHistogram& h );
933
934 static void AddHandler( wxImageHandler *handler );
935 static void InsertHandler( wxImageHandler *handler );
936 static bool RemoveHandler( const wxString& name );
937 %extend {
938 static PyObject* GetHandlers() {
939 wxList& list = wxImage::GetHandlers();
940 return wxPy_ConvertList(&list);
941 }
942 }
943
944 DocDeclStr(
945 static wxString , GetImageExtWildcard(),
946 "Iterates all registered wxImageHandler objects, and returns a string
947 containing file extension masks suitable for passing to file open/save
948 dialog boxes.", "");
949
950
951
952 MustHaveApp(ConvertToBitmap);
953 MustHaveApp(ConvertToMonoBitmap);
954
955 %extend {
956 wxBitmap ConvertToBitmap(int depth=-1) {
957 wxBitmap bitmap(*self, depth);
958 return bitmap;
959 }
960
961 wxBitmap ConvertToMonoBitmap( byte red,
962 byte green,
963 byte blue ) {
964 wxImage mono = self->ConvertToMono( red, green, blue );
965 wxBitmap bitmap( mono, 1 );
966 return bitmap;
967 }
968 }
969
970
971 DocDeclStr(
972 void , RotateHue(double angle),
973 "Rotates the hue of each pixel of the image. Hue is a double in the
974 range -1.0..1.0 where -1.0 is -360 degrees and 1.0 is 360 degrees", "");
975
976 DocDeclStr(
977 static wxImage_HSVValue , RGBtoHSV(wxImage_RGBValue rgb),
978 "Converts a color in RGB color space to HSV color space.", "");
979
980 DocDeclStr(
981 static wxImage_RGBValue , HSVtoRGB(wxImage_HSVValue hsv),
982 "Converts a color in HSV color space to RGB color space.", "");
983
984
985 %pythoncode { def __nonzero__(self): return self.Ok() }
986 };
987
988
989
990 // Make an image from buffer objects. Not that this is here instead of in the
991 // wxImage class (as a constructor) because there is already another one with
992 // the exact same signature, so there woudl be ambiguities in the generated
993 // C++. Doing it as an independent factory function like this accomplishes
994 // the same thing however.
995 %newobject _ImageFromBuffer;
996 %inline %{
997 wxImage* _ImageFromBuffer(int width, int height,
998 buffer data, int DATASIZE,
999 buffer alpha=NULL, int ALPHASIZE=0)
1000 {
1001 if (DATASIZE != width*height*3) {
1002 wxPyErr_SetString(PyExc_ValueError, "Invalid data buffer size.");
1003 return NULL;
1004 }
1005 if (alpha != NULL) {
1006 if (ALPHASIZE != width*height) {
1007 wxPyErr_SetString(PyExc_ValueError, "Invalid alpha buffer size.");
1008 return NULL;
1009 }
1010 return new wxImage(width, height, data, alpha, true);
1011 }
1012 return new wxImage(width, height, data, true);
1013 }
1014 %}
1015
1016 %pythoncode {
1017 def ImageFromBuffer(width, height, dataBuffer, alphaBuffer=None):
1018 """
1019 Creates a `wx.Image` from the data in dataBuffer. The dataBuffer
1020 parameter must be a Python object that implements the buffer interface, or
1021 is convertable to a buffer object, such as a string, array, etc. The
1022 dataBuffer object is expected to contain a series of RGB bytes and be
1023 width*height*3 bytes long. A buffer object can optionally be supplied for
1024 the image's alpha channel data, and it is expected to be width*height
1025 bytes long.
1026
1027 The wx.Image will be created with its data and alpha pointers initialized
1028 to the memory address pointed to by the buffer objects, thus saving the
1029 time needed to copy the image data from the buffer object to the wx.Image.
1030 While this has advantages, it also has the shoot-yourself-in-the-foot
1031 risks associated with sharing a C pointer between two objects.
1032
1033 To help alleviate the risk a reference to the data and alpha buffer
1034 objects are kept with the wx.Image, so that they won't get deleted until
1035 after the wx.Image is deleted. However please be aware that it is not
1036 guaranteed that an object won't move its memory buffer to a new location
1037 when it needs to resize its contents. If that happens then the wx.Image
1038 will end up referring to an invalid memory location and could cause the
1039 application to crash. Therefore care should be taken to not manipulate
1040 the objects used for the data and alpha buffers in a way that would cause
1041 them to change size.
1042 """
1043 if not isinstance(dataBuffer, buffer):
1044 dataBuffer = buffer(dataBuffer)
1045 if alphaBuffer is not None and not isinstance(alphaBuffer, buffer):
1046 alphaBuffer = buffer(alphaBuffer)
1047 image = _core_._ImageFromBuffer(width, height, dataBuffer, alphaBuffer)
1048 image._buffer = dataBuffer
1049 image._alpha = alphaBuffer
1050 return image
1051 }
1052
1053
1054 ///void wxInitAllImageHandlers();
1055
1056 %pythoncode {
1057 def InitAllImageHandlers():
1058 """
1059 The former functionality of InitAllImageHanders is now done internal to
1060 the _core_ extension module and so this function has become a simple NOP.
1061 """
1062 pass
1063 }
1064
1065
1066
1067 %immutable;
1068 const wxImage wxNullImage;
1069 %mutable;
1070
1071 //---------------------------------------------------------------------------
1072
1073 MAKE_CONST_WXSTRING(IMAGE_OPTION_FILENAME);
1074 MAKE_CONST_WXSTRING(IMAGE_OPTION_BMP_FORMAT);
1075 MAKE_CONST_WXSTRING(IMAGE_OPTION_CUR_HOTSPOT_X);
1076 MAKE_CONST_WXSTRING(IMAGE_OPTION_CUR_HOTSPOT_Y);
1077 MAKE_CONST_WXSTRING(IMAGE_OPTION_RESOLUTION);
1078 MAKE_CONST_WXSTRING(IMAGE_OPTION_RESOLUTIONX);
1079 MAKE_CONST_WXSTRING(IMAGE_OPTION_RESOLUTIONY);
1080 MAKE_CONST_WXSTRING(IMAGE_OPTION_RESOLUTIONUNIT);
1081 MAKE_CONST_WXSTRING(IMAGE_OPTION_QUALITY);
1082
1083 enum
1084 {
1085 wxIMAGE_RESOLUTION_INCHES = 1,
1086 wxIMAGE_RESOLUTION_CM = 2
1087 };
1088
1089
1090 MAKE_CONST_WXSTRING(IMAGE_OPTION_BITSPERSAMPLE);
1091 MAKE_CONST_WXSTRING(IMAGE_OPTION_SAMPLESPERPIXEL);
1092 MAKE_CONST_WXSTRING(IMAGE_OPTION_COMPRESSION);
1093 MAKE_CONST_WXSTRING(IMAGE_OPTION_IMAGEDESCRIPTOR);
1094
1095 MAKE_CONST_WXSTRING(IMAGE_OPTION_PNG_FORMAT);
1096 MAKE_CONST_WXSTRING(IMAGE_OPTION_PNG_BITDEPTH);
1097
1098 enum
1099 {
1100 wxPNG_TYPE_COLOUR = 0,
1101 wxPNG_TYPE_GREY = 2,
1102 wxPNG_TYPE_GREY_RED = 3
1103 };
1104
1105 enum
1106 {
1107 wxBMP_24BPP = 24, // default, do not need to set
1108 //wxBMP_16BPP = 16, // wxQuantize can only do 236 colors?
1109 wxBMP_8BPP = 8, // 8bpp, quantized colors
1110 wxBMP_8BPP_GREY = 9, // 8bpp, rgb averaged to greys
1111 wxBMP_8BPP_GRAY = wxBMP_8BPP_GREY,
1112 wxBMP_8BPP_RED = 10, // 8bpp, red used as greyscale
1113 wxBMP_8BPP_PALETTE = 11, // 8bpp, use the wxImage's palette
1114 wxBMP_4BPP = 4, // 4bpp, quantized colors
1115 wxBMP_1BPP = 1, // 1bpp, quantized "colors"
1116 wxBMP_1BPP_BW = 2 // 1bpp, black & white from red
1117 };
1118
1119
1120 DocStr(wxBMPHandler,
1121 "A `wx.ImageHandler` for \*.bmp bitmap files.", "");
1122 class wxBMPHandler : public wxImageHandler {
1123 public:
1124 wxBMPHandler();
1125 };
1126
1127 DocStr(wxICOHandler,
1128 "A `wx.ImageHandler` for \*.ico icon files.", "");
1129 class wxICOHandler : public wxBMPHandler {
1130 public:
1131 wxICOHandler();
1132 };
1133
1134 DocStr(wxCURHandler,
1135 "A `wx.ImageHandler` for \*.cur cursor files.", "");
1136 class wxCURHandler : public wxICOHandler {
1137 public:
1138 wxCURHandler();
1139 };
1140
1141 DocStr(wxANIHandler,
1142 "A `wx.ImageHandler` for \*.ani animated cursor files.", "");
1143 class wxANIHandler : public wxCURHandler {
1144 public:
1145 wxANIHandler();
1146 };
1147
1148
1149 //---------------------------------------------------------------------------
1150
1151 DocStr(wxPNGHandler,
1152 "A `wx.ImageHandler` for PNG image files.", "");
1153 class wxPNGHandler : public wxImageHandler {
1154 public:
1155 wxPNGHandler();
1156 };
1157
1158
1159 DocStr(wxGIFHandler,
1160 "A `wx.ImageHandler` for GIF image files.", "");
1161 class wxGIFHandler : public wxImageHandler {
1162 public:
1163 wxGIFHandler();
1164 };
1165
1166
1167 DocStr(wxPCXHandler,
1168 "A `wx.ImageHandler` for PCX imager files.", "");
1169 class wxPCXHandler : public wxImageHandler {
1170 public:
1171 wxPCXHandler();
1172 };
1173
1174
1175 DocStr(wxJPEGHandler,
1176 "A `wx.ImageHandler` for JPEG/JPG image files.", "");
1177 class wxJPEGHandler : public wxImageHandler {
1178 public:
1179 wxJPEGHandler();
1180 };
1181
1182
1183 DocStr(wxPNMHandler,
1184 "A `wx.ImageHandler` for PNM image files.", "");
1185 class wxPNMHandler : public wxImageHandler {
1186 public:
1187 wxPNMHandler();
1188 };
1189
1190 DocStr(wxXPMHandler,
1191 "A `wx.ImageHandler` for XPM image.", "");
1192 class wxXPMHandler : public wxImageHandler {
1193 public:
1194 wxXPMHandler();
1195 };
1196
1197 DocStr(wxTIFFHandler,
1198 "A `wx.ImageHandler` for TIFF image files.", "");
1199 class wxTIFFHandler : public wxImageHandler {
1200 public:
1201 wxTIFFHandler();
1202 };
1203
1204
1205 #if wxUSE_IFF
1206 DocStr(wxIFFHandler,
1207 "A `wx.ImageHandler` for IFF image files.", "");
1208 class wxIFFHandler : public wxImageHandler {
1209 public:
1210 wxIFFHandler();
1211 };
1212 #endif
1213
1214 //---------------------------------------------------------------------------
1215
1216 %{
1217 #include <wx/quantize.h>
1218 %}
1219
1220 enum {
1221 wxQUANTIZE_INCLUDE_WINDOWS_COLOURS,
1222 // wxQUANTIZE_RETURN_8BIT_DATA,
1223 wxQUANTIZE_FILL_DESTINATION_IMAGE
1224 };
1225
1226
1227 DocStr(wxQuantize,
1228 "Performs quantization, or colour reduction, on a wxImage.", "");
1229
1230 class wxQuantize /*: public wxObject */
1231 {
1232 public:
1233
1234 %extend {
1235 DocStr(
1236 Quantize,
1237 "Reduce the colours in the source image and put the result into the
1238 destination image, setting the palette in the destination if
1239 needed. Both images may be the same, to overwrite the source image.", "
1240 :todo: Create a version that returns the wx.Palette used.");
1241
1242 static bool Quantize(const wxImage& src, wxImage& dest, int desiredNoColours = 236,
1243 int flags = wxQUANTIZE_INCLUDE_WINDOWS_COLOURS|wxQUANTIZE_FILL_DESTINATION_IMAGE)
1244 {
1245 return wxQuantize::Quantize(src, dest,
1246 //NULL, // palette
1247 desiredNoColours,
1248 NULL, // eightBitData
1249 flags);
1250 }
1251 }
1252 };
1253
1254
1255 //---------------------------------------------------------------------------