Generating an in memory image for tests in Python

When writing tests for Django, you often need to simulate file uploads without creating junk files on your disk. Using Python's io module and the PIL (Pillow) library, you can easily generate an image file in memory.

The Implementation

from PIL import Image
import io

def generate_in_memory_image(format='PNG'):
    file = io.BytesIO()
    image = Image.new('RGB', size=(100, 100), color=(255, 0, 0))
    image.save(file, format)
    file.name = 'test.png'
    file.seek(0)
    return file

You can then pass this object into your Django SimpleUploadedFile when testing forms or API endpoints.