Search code examples
pythonimagepython-imaging-librarycrop

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'>

Solution

  • 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.