Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert pillow Image object to JpegImageFile object

I cropped an jpeg image, but the cropped image type is

<class 'PIL.Image.Image'>

how can i convert it to

<class 'PIL.JpegImagePlugin.JpegImageFile'>

?

thank you!

import requests
from PIL import Image
from io import BytesIO

img = Image.open(BytesIO(requests.get("https://mamahelpers.co/assets/images/faq/32B.JPG").content))
img2 = img.crop((1,20,50,80))

print(type(img)) # <class 'PIL.JpegImagePlugin.JpegImageFile'>
print(type(img2)) # <class 'PIL.Image.Image'>
like image 578
Martin Avatar asked Mar 06 '23 16:03

Martin


1 Answers

If you do not want a pyhsical file, do use a memory file:

import requests
from PIL import Image
from io import BytesIO    

img = Image.open(BytesIO(requests.get("https://mamahelpers.co/assets/images/faq/32B.JPG").content))
img2 = img.crop((1,20,50,80))

b = BytesIO()
img2.save(b,format="jpeg")
img3 = Image.open(b)

print(type(img))  # <class 'PIL.JpegImagePlugin.JpegImageFile'>
print(type(img2)) # <class 'PIL.Image.Image'> 
print(type(img3)) # <class 'PIL.JpegImagePlugin.JpegImageFile'>

ByteIO is a stream-obj, it is probably wise to close() it at some point when no longer needed.

like image 147
Patrick Artner Avatar answered Mar 16 '23 21:03

Patrick Artner