Search code examples
pythoniconswxpythonpython-imaging-librarypadding

Padding an image for use in wxpython


I'm looking for the most efficient way to 'square' an image for use as an icon. For example, I've got a .png file whose dimensions are 24x20.I don't want to change the 'image' part of the image in any way, I just want to add transparent pixels to the edge of the image so it becomes 24x24. My research suggests that I need to create a transparent canvas 24x24, paste my image on to this, then save the result. I'm working in wxpython and was wondering if anyone could guide me through the process. Better yet, I also have PIL installed, and was wondering if there wasn't a built-in way of doing this. It seems like the kind of operation that would be carried out fairly regularly, but none of the imageops methods quite fit the bill.


Solution

  • Use image.paste to paste the image on a transparent background:

    import Image
    FNAME = '/tmp/test.png'
    top = Image.open(FNAME).convert('RGBA')
    new_w = new_h = max(top.size)
    background = Image.new('RGBA', size = (new_w,new_h), color = (0, 0, 0, 0))
    background.paste(top, (0, 0))
    background.save('/tmp/result.png')