【问题标题】:convert pillow Image object to JpegImageFile object将枕头 Image 对象转换为 JpegImageFile 对象
【发布时间】:2019-01-14 11:40:34
【问题描述】:

我裁剪了一张 jpeg 图像,但裁剪后的图像类型是

<class 'PIL.Image.Image'>

如何转换成

<class 'PIL.JpegImagePlugin.JpegImageFile'>

谢谢!

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

【问题讨论】:

  • @PatrickArtner 已经看到了这个问题,解决方案在我的情况下不起作用
  • 最好引用您在帖子中研究过的问题 - 我们应该如何知道您已经尝试过什么,什么没有奏效?为什么它在你的情况下不起作用?将您的 PIL.Image.Image 转换为 RGB,将其保存为 JPG,使用 myfile = PIL.JpegImagePlugin.JpegImageFile('filename.jpg') 重新打开它?
  • @PatrickArtner 写入磁盘的操作成本太高,这就是我向社区寻求另一种解决方案的原因。 UPD:包含问题的代码

标签: python image python-imaging-library crop


【解决方案1】:

如果您不想要物理文件,请使用内存文件:

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 是一个流 obj,在某个不再需要的时候close() 它可能是明智的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 2021-08-05
    • 2020-09-30
    • 2018-06-03
    • 1970-01-01
    • 2016-10-31
    • 2023-04-03
    相关资源
    最近更新 更多