[Fixed]-Generate 1MB image python

2πŸ‘

βœ…

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
πŸ‘€David Wolever

-1πŸ‘

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.

πŸ‘€neutrinus

Leave a comment