简体   繁体   English

使用我自己的cothon与python和PIL裁剪透明的PNG图像

[英]Crop transparent PNG image with my own coords with python and PIL

Now my code write PNG, but I can't open it - errors of file. 现在我的代码写了PNG,但我无法打开它 - 文件错误。 Without crooping all works, but I need crop png file. 没有弯曲所有的作品,但我需要裁剪png文件。 With my coords (no PIL box), and transparent images. 用我的坐垫(没有PIL盒)和透明图像。

Image.open(imagefile)
#image = image.crop(crop_coords) #only work without cropping

image.thumbnail([x, y], Image.ANTIALIAS)

imagefile = StringIO()
imagefile = open(file_destination, 'w')
try:
    image.save(imagefile, "PNG", quality=90)
except:
    print "Cannot save user image"

Thanks for help. 感谢帮助。


I have noticed that problem is only for png files with indexed PNG alpha images. 我注意到问题仅适用于带有索引PNG alpha图像的png文件。

from PIL import Image
#from StringIO import StringIO

img = Image.open("foobar.png")

png_info = {}
if img.mode not in ['RGB','RGBA']:
        img = img.convert('RGBA')
        png_info = img.info

img = img.crop( (0,0,400,400) )

img.thumbnail([200, 200], Image.ANTIALIAS)

file_destination='quux.png'

# imagefile = StringIO()
imagefile = open(file_destination, 'wb')
try:
    img.save(imagefile, "png", quality=90, **png_info)
    imagefile.close()
except:
    print "Cannot save user image"

thanks for: PIL does not save transparency 谢谢: PIL不能保存透明度

You must open the file in binary mode, otherwise it will write something but file may be corrupted. 您必须以二进制模式打开文件,否则它会写一些文件但文件可能已损坏。 According to the test you do, the file will be corrupted or not, that may not be because of the crop itself. 根据您的测试,文件将被破坏或不被破坏,这可能不是因为作物本身。

Here is a working version I made: 这是我制作的一个工作版本:

from PIL import Image
#from StringIO import StringIO

img = Image.open("foobar.png")
img = img.crop( (0,0,400,400) )

img.thumbnail([200, 200], Image.ANTIALIAS)

file_destination='quux.png'

# imagefile = StringIO()
imagefile = open(file_destination, 'wb')
try:
    img.save(imagefile, "png", quality=90)
    imagefile.close()
except:
    print "Cannot save user image"

Here is a simple solution using numpy and Pillow, just change the questionmarks with your own coords! 这是一个使用numpy和Pillow的简单解决方案,只需用自己的坐标更改问号!

from PIL import Image
import numpy as np

def crop(png_image_name):
    pil_image = Image.open(png_image_name)
    np_array = np.array(pil_image)
    # z is the alpha depth, leave 0
    x0, y0, z0 = (?, ?, 0) 
    x1, y1, z1 = (?, ?, 0) 
    cropped_box = np_array[x0:x1, y0:y1, z0:z1]
    pil_image = Image.fromarray(cropped_box, 'RGBA')
    pil_image.save(png_image_name)

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

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