Reputation: 2197
i have been trying a few solutions that i found here but non of the is able to pass validation by https://docs.python.org/3.8/library/imghdr.html IMGHDR built-in python module via imghdr.what()
method.
Question is - is it possible generate in-memory image file in a such a way that it would pass validation by imghdr.what()
???
Needed for Django tests.
Thanks.
Upvotes: 0
Views: 543
Reputation: 18106
You can write a (dummy) image to memory and read it from there using BytesIO:
from PIL import Image
from io import BytesIO
import imghdr
def dummyImage(imgFormat):
storage = BytesIO()
img = Image.new("RGB", (640, 480))
img.save(storage, imgFormat)
storage.seek(0) # important for imghdr to read from the beginning!
imgType = imghdr.what('test', h=storage.read()) # what() needs a dummy filename!
return imgType
for imgFormat in ('PNG', 'BMP', 'JPEG'):
print(dummyImage(imgFormat))
Ouput:
png
bmp
jpeg
Upvotes: 1