Images and bitmaps in wxPython are normally created by loading files from disk. Working with the images in memory is, however, a common task for certain types of application. This recipe set looks at the in-memory manipulation (and particularly the generation) of images for use in wxPython applications.

Table of Contents: TableOfContents

Formats and Conversions

PIL (Python Imaging Library)

        def GetBitmap( self ):
                import Image
                source = Image.open( r"Z:\mcfport\portfoli\full\claire.jpg", 'r')
                image = apply( wxEmptyImage, source.size )
                image.SetData( source.convert( "RGB").tostring() )
                return image.ConvertToBitmap() # wxBitmapFromImage(image)

Numeric Python

        def GetBitmap( self, width=32, height=32, colour = (0,0,0) ):
                array = Numeric.zeros( (height, width, 3),'c')
                array[:,:,] = colour
                image = wxEmptyImage(width,height)
                image.SetData( array.tostring())
                return image.ConvertToBitmap()# wxBitmapFromImage(image)

Slicing

Examples

        def GetBitmap( self, width=32, height=32, colour = (128,128,128), border=5, borderColour=(255,255,255) ):
                # creates a bitmap with a border
                array = Numeric.zeros( (height, width, 3),'c')
                array[border:-border,border:-border,:] = colour
                array[:border,:,:] = borderColour
                array[-border:,:,:] = borderColour
                array[:,:border,:] = borderColour
                array[:,-border:,:] = borderColour
                image = wxEmptyImage(width,height)
                image.SetData( array.tostring())
                return image.ConvertToBitmap()# wxBitmapFromImage(image)

        def GetBitmap( self ):
                ## Create a 256-level gradiant
                array = Numeric.zeros( (height, width, 3),'c')
                array[:,:,0] = range( 256 )
                image = wxEmptyImage(width,height)
                image.SetData( array.tostring())
                return image.ConvertToBitmap()# wxBitmapFromImage(image)

Screen Capture

        def OnToFile( self, event ):
                context = wxPaintDC( self )
                memory = wxMemoryDC( )
                x,y = self.GetClientSizeTuple()
                bitmap = wxEmptyBitmap( x,y, -1 )
                memory.SelectObject( bitmap )
                memory.Blit( 0,0,x,y, context, 0,0)
                memory.SelectObject( wxNullBitmap)
                bitmap.SaveFile( "test.bmp", wxBITMAP_TYPE_BMP )
NOTE: To edit pages in this wiki you must be a member of the TrustedEditorsGroup.