裁剪时将图像类型信息保留在PIL中 [英] Preserving image type info in PIL when cropping

查看:63
本文介绍了裁剪时将图像类型信息保留在PIL中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Etienne的从此处对Python的PIL进行的出色修改.我需要的正是修改的内容-使用与原始量化表相同的量化表保存JPEG文件.通过这种修改来完成它似乎很不错,我目前正在通过使用C语言的杂烩来实现.

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.

我的问题是我在PIL中获得了一个JPEG文件对象,但是在进行任何修改后,它变成了某种其他类型的对象.我想要的是拍摄图像,裁剪并保存在相同的量化表中.

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.

我尝试:

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

img对象首先是一个PIL.JpegImagePlugin.JpegImageFile,但是在调整大小/粘贴操作之后,它只是一个Image.因此,由于它不再是JPEG,因此我不能使用quality ='keep'.我如上所述尝试了裁剪和粘贴,还尝试了其他几种方法,但是似乎没有任何方法可以保留JpegImageFile对象.

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.

推荐答案

如果您使用的是我想您是艾蒂安(Etienne)的叉子,那么您应该可以执行以下操作:

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)

有关更多信息,请参见此文档由Etienne

See this documentation by Etienne for more info.

这篇关于裁剪时将图像类型信息保留在PIL中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆