Note that there are some explanatory texts on larger screens.

plurals
  1. POScale images with PIL preserving transparency and color?
    primarykey
    data
    text
    <p>Say you want to scale a transparent image but do not yet know the color(s) of the background you will composite it onto later. Unfortunately PIL seems to incorporate the color values of fully transparent pixels leading to bad results. Is there a way to tell PIL-resize to ignore fully transparent pixels?</p> <pre><code>import PIL.Image filename = "trans.png" # http://qrc-designer.com/stuff/trans.png size = (25,25) im = PIL.Image.open(filename) print im.mode # RGBA im = im.resize(size, PIL.Image.LINEAR) # the same with CUBIC, ANTIALIAS, transform # im.show() # does not use alpha im.save("resizelinear_"+filename) # PIL scaled image has dark border </code></pre> <p><img src="https://i.stack.imgur.com/i4BpL.png" alt="original image with (0,0,0,0) black but fully transparent background"> <img src="https://i.stack.imgur.com/ZETHA.png" alt="output image with black halo"> <img src="https://i.stack.imgur.com/xvoOO.png" alt="proper output scaled with gimp"></p> <p>original image with (0,0,0,0) (black but fully transparent) background (left)</p> <p>output image with black halo (middle)</p> <p>proper output scaled with gimp (right)</p> <p>edit: It looks like to achieve what I am looking for I would have to modify the sampling of the resize function itself such that it would ignore pixels with full transparency. </p> <p>edit2: I have found a very ugly solution. It sets the color values of fully transparent pixels to the average of the surrounding non fully transparent pixels to minimize impact of fully transparent pixel colors while resizing. It is slow in the simple form but I will post it if there is no other solution. Might be possible to make it faster by using a dilate operation to only process the necessary pixels.</p> <p>edit3: premultiplied alpha is the way to go - see Mark's answer</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload