Look at something like PIL :
A simple example :
And whilst not directly related to what you’re trying to do, here’s PIL being used in Anvil to generate images :