convert pillow Image object to JpegImageFile object

我是研究僧i 提交于 2020-07-20 20:24:11

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/51725809/convert-pillow-image-object-to-jpegimagefile-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!