Preserving image type info in PIL when cropping

陌路散爱 提交于 2021-02-08 03:31:34

问题


I am using the excellent modification to Python's PIL by Etienne from here. What I need is exactly what the modification does - to save a JPEG file using the same quantization tables as the original. Doing it through that modification seems elegant, I'm currently achieving that by using a hodgepodge of C code.

My problem is that I get a JPEG file object in PIL, but after any modification it becomes an object of some other type. What I want is to take the image, crop it and save it with the same quantization table.

I try:

img = Image.open("someimage.jpg")
width, height = img.size
crop = img.crop((8, 0, width, height))
img = img.resize((width - 8, height))
img.paste(crop, (0,0))
img.save("crop.jpg", quality='keep')

The img object is first a PIL.JpegImagePlugin.JpegImageFile but becomes just an Image after the resize/paste operation. So consequently I can't use quality='keep' as it's no longer a JPEG. I've tried cropping and pasting as above, I tried a few other ways but nothing seems to preserve the JpegImageFile object.


回答1:


If you are using this fork by Etienne, which I think you are, then you should be able to do something like this:

img = Image.open("someimage.jpg")
qt = img.quantization
# qt is now a dictionary of arrays which is your quantization table.

width, height = img.size
crop = img.crop((8, 0, width, height))
img = img.resize((width - 8, height))
img.paste(crop, (0,0))

# pass qt in as you save your jpeg
img.save("crop.jpg",  qtables = qt)

See this documentation by Etienne for more info.



来源:https://stackoverflow.com/questions/9672442/preserving-image-type-info-in-pil-when-cropping

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