简体   繁体   English

Python PIL和PILLOW如何压缩图片?

[英]How does Python PIL and PILLOW compress pictures?

I wanted to write a program with Python 3.3 in which a frame is added to a picture. 我想用Python 3.3编写一个程序,其中一个帧被添加到图片中。 I use the PIL package from Python to do that. 我使用Python的PIL包来做到这一点。 But the pictures I get are less than a third as big as the original and they loose quite some focus/sharpness/gloss. 但是我得到的照片不到原来的三分之一,并且它们散开了相当多的焦点/清晰度/光泽度。 Where does Python compress/change the picture and how (if possible) can I subdue it? Python在哪里压缩/更改图片以及如何(如果可能)我可以将其压缩?

I could think of some passages, which might be the one compressing. 我可以想到一些段落,可能是压缩的段落。

  1. I load the image with PIL: 我用PIL加载图像:

    img = Image.open(element)

  2. I create a new picture, which is black: 我创建了一张黑色的新图片:

    newImg = Image.new("RGB",(imgWidthNew,imgHightNew),(0,0,0,0))

  3. I create a pixel map out of my picture and change some: 我从我的图片中创建一个像素图并更改一些:

    pixels = newImg.load()

  4. I paste my picture into the middle of the black one: 我将照片粘贴到黑色照片的中间:

    newImg.paste (Image.open(element), (halfFrameWidth, halfFrameHight, imgWidth+halfFrameWidth, imgHight+halfFrameHight))

  5. The new image is beeing saved: 新图像正在保存:

    newImg.save(path,dpi=[300,300])

I load mostly .jpg pictures, but due to some problems I extract .bmp files. 我主要加载.jpg图片,但由于一些问题,我提取.bmp文件。

 path = path[:path.rfind(".")] + fileEnding

But this shouldnt be the problem, because I have the same issues without changing the data type. 但这不应该是问题,因为我有相同的问题而不改变数据类型。 My operating system is Windows7 64BIT and I use Pillow 2.3.0 with Python 3.3. 我的操作系统是Windows7 64BIT,我使用Pillow 2.3.0和Python 3.3。

Thank you for any help. 感谢您的任何帮助。

When saving as JPEG, you can set the quality parameter to control the amount of compression: 保存为JPEG时,您可以设置质量参数来控制压缩量:

newImg.save(path, 'JPEG', dpi=[300,300], quality=90)

Or, save in a lossless format, such as PNG: 或者,以无损格式保存,例如PNG:

newImg.save(path, 'PNG', dpi=[300,300])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM