[英]Crop transparent PNG image with my own coords with python and PIL
現在我的代碼寫了PNG,但我無法打開它 - 文件錯誤。 沒有彎曲所有的作品,但我需要裁剪png文件。 用我的坐墊(沒有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"
感謝幫助。
我注意到問題僅適用於帶有索引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"
謝謝: PIL不能保存透明度
您必須以二進制模式打開文件,否則它會寫一些文件但文件可能已損壞。 根據您的測試,文件將被破壞或不被破壞,這可能不是因為作物本身。
這是我制作的一個工作版本:
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"
這是一個使用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.