Question

Now my code write PNG, but I can't open it - errors of file. Without crooping all works, but I need crop png file. With my coords (no PIL box), and transparent images.

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.

Was it helpful?

Solution 2

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"

OTHER TIPS

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

Here is a simple solution using numpy and Pillow, just change the questionmarks with your own coords!

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top