4

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'>
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Martin
  • 113
  • 1
  • 2
  • 8
  • Possible duplicate of [Convert to jpeg using Pillow in python](https://stackoverflow.com/questions/43258461/convert-png-to-jpeg-using-pillow-in-python) – Patrick Artner Aug 07 '18 at 11:37
  • @PatrickArtner already seen this question, solution didn't worked in my case – Martin Aug 07 '18 at 11:44
  • Its good to cite questions you researched in your post - how should we know what you already tried and what did not work? Why did it not work in your case? Convert your PIL.Image.Image to RGB, save it as JPG, Reopen it using `myfile = PIL.JpegImagePlugin.JpegImageFile('filename.jpg')` ? – Patrick Artner Aug 07 '18 at 11:46
  • @PatrickArtner writing to disk is too expensive operation, that's why i'm asking from a community for another solution. UPD: included code to question – Martin Aug 07 '18 at 11:51

1 Answers1

7

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.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69