[Fixed]-Generate in-memory image for Django testing

1👍

Thanks to help from Eduardo, I was able to get a working solution.

from StringIO import StringIO
import Image

file = StringIO()
image = Image.new("RGBA", size=(50,50), color=(256,0,0))
image.save(file, 'png')
file.name = 'test.png'
file.seek(0)

15👍

To generate a 200×200 test image of solid red:

import Image
size = (200,200)
color = (255,0,0,0)
img = Image.new("RGBA",size,color)

To convert it to a file-like object, then:

import StringIO
f = StringIO.StringIO(img.tostring())

http://effbot.org/imagingbook/image.htm

14👍

Jason’s accepted answer is not working for me in Django 1.5

Assuming the generated file is to be saved to a model’s ImageField from within a unit test, I needed to take it a step further by creating a ContentFile to get it to work:

from PIL import Image
from StringIO import StringIO

from django.core.files.base import ContentFile

image_file = StringIO()
image = Image.new('RGBA', size=(50,50), color=(256,0,0))
image.save(image_file, 'png')
image_file.seek(0)

django_friendly_file = ContentFile(image_file.read(), 'test.png')
👤dshap

4👍

So if client.post is expecting a file like object, you could create an example image (if you want to visually check result after tests) or just make a 1px png and read it out from console

open('1px.png', 'rb').read()

which in my case dumped out

image_data = '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\tpHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07\xdb\x0c\x17\x020;\xd1\xda\xcf\xd2\x00\x00\x00\x0cIDAT\x08\xd7c\xf8\xff\xff?\x00\x05\xfe\x02\xfe\xdc\xccY\xe7\x00\x00\x00\x00IEND\xaeB`\x82'

then you can use StringIO which acts as a file like object, so above, image would be

from StringIO import StringIO

def test_issue_add_post(self):
    ...
    image = StringIO(image_data)
    ...

and you’ll have a file like object with the image data

4👍

In Python 3

from io import BytesIO
from PIL import Image

image = Image.new('RGBA', size=(50, 50), color=(155, 0, 0))
file = BytesIO(image.tobytes())
file.name = 'test.png'
file.seek(0)
#  + + + django_friendly_file = ContentFile(file.read(), 'test.png') # year 2019, django 2.2.1  -works 

0👍

Have you used the PIL module? It lets you manipulate images – and should allow creation as well.

In fact, here’s a blog entry with some code that does it
http://bradmontgomery.blogspot.com/2008/07/django-generating-image-with-pil.html

Dont know whether you test machine has an internet connection, but you could also pull down random images from google to vary the test data?

👤suhail

Leave a comment