用python和PIL裁剪透明的PNG图像

2024-09-28 03:21:23 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我的代码写PNG,但我不能打开它-错误的文件。 没有低声的所有作品,但我需要裁剪png文件。用我的坐标(没有PIL-box)和透明图像。在

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"

谢谢你的帮助。在


我注意到这个问题只存在于png文件和索引png alpha图像。在


Tags: 文件代码图像cropimagepilpngsave
3条回答

您必须以二进制模式打开该文件,否则它将写入某些内容,但文件可能已损坏。根据您所做的测试,文件是否会损坏,这可能不是因为裁剪本身。在

以下是我制作的工作版本:

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

感谢您: PIL does not save transparency

这里有一个简单的解决方案,使用纽比和枕头,只要改变你自己的坐标问号!在

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)

相关问题 更多 >

    热门问题