Reputation: 7318
from PIL import Image
myImg = request.FILES['docfile']
myImg = Image.open(myImg)
print(myImg.format, myImg.size, myImg.mode)
myImg = myImg.resize((50, 50))
print(myImg.format, myImg.size, myImg.mode)
Here is an abridged version of a (django/ python 3.5) code. The goal is to resize an image (i don't want to use thumbnails for this), but keep it in memory, not save it to disk (yet) since I must pass it back into array.
Anyway, here are the results of the 2 prints:
PNG (1300, 1300) RGBA
None (50, 50) RGBA
As you can see, the format is lost after the resize. How can I preserve it ?
Upvotes: 2
Views: 1491
Reputation: 4504
To preserve the format, you could do:
myImg = Image.open(myImg)
myImg2 = myImg.resize((50, 50))
myImg2.format = myImg.format
Upvotes: 0
Reputation: 13616
As the doc says:
PIL.Image.format
The file format of the source file. For images created by the library itself (via a factory function, or by running a method on an existing image), this attribute is set to
None
.
After you resize the image it becomes “created by the library”, so if you want to preserve the format, you have to do this explicitly.
Also note that format is the property of the source file, not the image itself. The image itself is just an abstract set of pixels stored in the memory in some way. So it makes no sense to ask what is the format of an image. It makes sense to ask what is the format of a file which contains an image. So the image has no format until you write it to a file (or encode into some format for this purpose).
Upvotes: 4
Reputation: 10028
As I remember items in FILES
collection is like streams, i.e. once read you must set position to the beginning again. For example, you could load content to StringIO
object, then create image from it, then call seek(0)
on it and create thumbnail from that object again.
Upvotes: 0