Image padding for use in wxpython

I am looking for the most efficient way to "square" an image to use as an icon. For example, I have a .png file that is 24x20 in size. I do not want to change part of the image in the image in any way, I just want to add transparent pixels to the edge of the image so that it becomes 24x24. My research shows that I need to create a 24x24 transparent canvas, paste the image on it, and then save the result. I work in wxpython and wonder if anyone can help me in this process. Even better, I also installed PIL and wondered if there was such a built-in way to do this. It seems that such an operation will be carried out quite regularly, but none of the image methods are suitable for the bill.

+5
source share
3 answers

Use image.paste to paste the image onto 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')
+3
source

You can do this with a numpy array quite easily .. something like this

import matplotlib.pyplot as plt
import numpy as np
im1 = plt.imread('your_im.png')
im0 = np.zeros((24, 24, 4), dtype=im1.dtype)
im0[2:-2,:,:] = im1
plt.imsave('your_new_im.png', im0)
+3
source

This is where the pure wxPython implementation runs.

import wx

app = wx.PySimpleApp()

# load input bitmap
bitmap = wx.Bitmap('input.png')

# compute dimensions
width, height = bitmap.GetSize()
size = max(width, height)
dx, dy = (size - width) / 2, (size - height) / 2

# create output bitmap
new_bitmap = wx.EmptyBitmap(size, size)
dc = wx.MemoryDC(new_bitmap)
dc.SetBackground(wx.Brush(wx.Colour(255, 0, 255)))
dc.Clear()
dc.DrawBitmap(bitmap, dx, dy)
del dc

# save output
image = wx.ImageFromBitmap(new_bitmap)
image.SetMaskColour(255, 0, 255)
image.SaveFile('output.png', wx.BITMAP_TYPE_PNG)
+1
source

All Articles