Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PNG Image Quality in PIL

Have been trying to upload the following png file to google cloud storage through app engine:

enter image description here

Before the upload, I'm running this through PIL to take care of any image rotations or changes in background color etc

However, I'm getting really bad image quality when running PIL manipulations through the app even though running the same commands in python command line comes out fine

enter image description here

Anybody have ideas?

For the PIL commands, I'm just running the following:

imtemp = Image.open('/[path]/logo.png')
size = max(imtemp.size[0],imtemp.size[1]) 
im = Image.new('RGBA', (size,size), (255,255,255,0))
im.paste(imtemp, ((size-imtemp.size[0])/2,(size-imtemp.size[1])/2)) 
imtemp = im 
im = Image.new('RGB', (size,size), '#FFFFFF') 
im.paste(imtemp, (0,0), imtemp) 
im.show()

Have tried below, but still no luck

    imtemp = Image.open(StringIO(imagedata)).convert("RGBA")
    im = Image.new("RGB", imtemp.size, "#FFFFFF")
    im.paste(imtemp, None, imtemp)
    imageoutput = StringIO()
    im.save(imageoutput, format="PNG", quality=85, optimize=True, progressive=True)
    imageoutput = imageoutput.getvalue()
like image 844
Dennis Avatar asked Oct 12 '25 10:10

Dennis


1 Answers

It looks like you want to take a palettized image, possibly with transparent pixels, project it on a white background and make a quality-resized version of it which is half as big.

You can use the convert() and thumbnail() function for this:

from PIL import Image

# Open the image and convert it to RGBA.
orig = Image.open("fresh.png").convert("RGBA")

# Paste it onto a white background.
im = Image.new("RGB", orig.size, "#ffffff")
im.paste(orig, None, orig)

# Now a quality downsize.
w, h = im.size
im.thumbnail((w / 2, h / 2), Image.ANTIALIAS)
im.show()    

Of course, you can leave the thumbnail() call out if you want the image at the original size.

like image 189
Michiel Overtoom Avatar answered Oct 15 '25 00:10

Michiel Overtoom