Skip to content

Instantly share code, notes, and snippets.

@philiptzou
Created June 25, 2014 02:45
Show Gist options
  • Save philiptzou/2917008ccb5f5493d6bb to your computer and use it in GitHub Desktop.
Save philiptzou/2917008ccb5f5493d6bb to your computer and use it in GitHub Desktop.
Random string and random image by Python
import random
try:
from io import StringIO
except ImportError:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from PIL import Image
def randstr(size=16):
"""Generates random string
Parameters:
- size: integer, string size in byte
returns: bytes, random string with `size` bytes
"""
return (hex(random.randint(0, 2 ** (size * 8)))[2:]
.rstrip('L').rjust(size * 2, '0')
.decode('hex'))
def randimg(size(100, 100), format='PNG'):
"""Generates random image
Parameters:
- size: tuple(width, height), width and height of the image in pixel
- format: string, any type that PIL accepted
returns: bytes of the random image
"""
im = Image.fromstring('RGBA', size,
randstr(size[0] * size[1] * 4))
dstio = StringIO()
im.save(dstio, format)
return dstio.getvalue()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment