Giovanni Cornachini
Giovanni Cornachini

Reputation: 161

Generate 1MB image python

I need to generate 1MB image file to do a teste on django. I can only set the image size, but not the image file size.

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

Upvotes: 0

Views: 641

Answers (2)

neutrinus
neutrinus

Reputation: 2009

File size depends on what is on the picture. PNG compresses the data, so the blank image would be way smaller than a photo (with the same resolution).

You may use an iterative approach: filp one pixel, save to file, check size. Then flip another one. Faster: use bisection.

Upvotes: -1

David Wolever
David Wolever

Reputation: 154504

The simplest way is to save a BMP image, which has no compression:

In [1]: Image.new('L', (1024, 1024)).save('/tmp/x.bmp')
In [2]: !ls -alh /tmp/x.bmp
-rw-r--r--  1 wolever  wheel   1.0M Jul 13 16:46 /tmp/x.bmp

And if you need to use PNG, you can fill it with random data:

In [3]: import os
In [4]: Image.frombytes('L', (1024, 1024), os.urandom(1024*1024)).save('/tmp/x.png')
In [5]: !ls -alh /tmp/x.png
-rw-r--r--  1 wolever  wheel   1.0M Jul 13 16:49 /tmp/x.png

Upvotes: 2

Related Questions