rreg101
rreg101

Reputation: 209

Transparency not showing in Python after I cropped it and added transparency

I am trying to open an image that I added transparent corners to. I save it as a .png and when I open it in python the corners are still there but when I open the same image in preview the edges are present. I am also using Pillow for my image processing.

Also the image that I am trying to add rounded corners on is a black and white "1" bit pixel depth. I have also tried converting it to "RGBA" before and after adding corners I also tried the same with "RGB" to no avail.

Here is the method that I am using to make the transparent corners.

from PIL import Image, ImageChops, ImageOps, ImageDraw
'''
http://stackoverflow.com/questions/11287402/how-to-round-corner-a-logo-without-white-backgroundtransparent-on-it-using-pi
'''
def add_corners(self, im, rad):
    circle = Image.new('L', (rad * 2, rad * 2), 0)
    draw = ImageDraw.Draw(circle)
    draw.ellipse((0, 0, rad * 2, rad * 2), fill=255)
    alpha = Image.new('L', im.size, 255)
    w, h = im.size
    alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))
    alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad))
    alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w - rad, 0))
    alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w - rad, h - rad))
    im.putalpha(alpha)
    return im

Upvotes: 0

Views: 205

Answers (1)

Martin Evans
Martin Evans

Reputation: 46779

The function as you have it should work perfectly. You can pass it something like a JPG image, but you must save the resulting file in PNG format as JPG does not support transparency. For example:

img = Image.open('test.jpg')
img_corners = add_corners(img, 40)
img_corners.save('with_corners.png')

Note, if img_corners.show() is used, on Windows this will cause the library to create a temporary file in BMP format which does not support the transparency layer.

Upvotes: 1

Related Questions