0

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
rreg101
  • 209
  • 1
  • 9
  • 1
    How are you calling the function? For example, you can pass it a JPG file but you must save the return as a PNG otherwise the transparency information will be lost. – Martin Evans Jun 03 '16 at 07:15
  • `img2 = add_corners("theFirst.png") img2.save("1234.png", **png_info) img3 = Image.open("1234.png") img3.show()` and it still wont show the changes I applied. But it saves it correctly, really weird. – rreg101 Jun 06 '16 at 01:24
  • 1
    If you are using Windows, `show()` will display your image as a BMP which unfortunately also does not support transparency. – Martin Evans Jun 06 '16 at 08:24
  • I am using a Mac, I wonder if it has the same problem – rreg101 Jun 07 '16 at 02:49
  • 1
    I can't say for a Mac, but on Windows it does show the name of the temporary file being displayed at the top of the window, this shows it has a BMP extension. – Martin Evans Jun 08 '16 at 06:52
  • I believe it is the same for Mac, thank you so much! – rreg101 Jun 08 '16 at 07:35

1 Answers1

1

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.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97