7

Decided to try PIL lib in jupyter notebook. I have an image of blue color (nothing else) in png format.

Wanted to make it half-transparent. So I did:

from PIL import Image
blue = Image.open("blue_color.png")

When I open the image through jupyter, everything is fine. But then I apply .putalpha() method:

blue.putalpha(128)

And get this:

KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\PIL\PngImagePlugin.py in _save(im, fp, filename, chunk)
    799     try:
--> 800         rawmode, mode = _OUTMODES[mode]
    801     except KeyError:

KeyError: 'PA'

During handling of the above exception, another exception occurred:

OSError                                   Traceback (most recent call last)
~\Anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    343             method = get_real_method(obj, self.print_method)
    344             if method is not None:
--> 345                 return method()
    346             return None
    347         else:

~\Anaconda3\lib\site-packages\PIL\Image.py in _repr_png_(self)
    698         """
    699         b = io.BytesIO()
--> 700         self.save(b, "PNG")
    701         return b.getvalue()
    702 

~\Anaconda3\lib\site-packages\PIL\Image.py in save(self, fp, format, **params)
   2082 
   2083         try:
-> 2084             save_handler(self, fp, filename)
   2085         finally:
   2086             # do what we can to clean up

~\Anaconda3\lib\site-packages\PIL\PngImagePlugin.py in _save(im, fp, filename, chunk)
    800         rawmode, mode = _OUTMODES[mode]
    801     except KeyError:
--> 802         raise IOError("cannot write mode %s as PNG" % mode)
    803 
    804     #

OSError: cannot write mode PA as PNG

Made the same actions with another file of color, but it was in jpg format. And everything was fine!

Is it a file format problem? Could anyone tell me how to fix this?

Thanks in advance!

Yoda_babe
  • 71
  • 1
  • 5

1 Answers1

3

You can convert the png to jpg first.

im = Image.open("blue_color.png")
rgb_im = im.convert('RGB')
rgb_im.save('blue_color.jpg')
fcmdhyd
  • 47
  • 4
  • 1
    This doesn't address OP's question of creating a half transparent blue rectangle. JPEG doesn't even support alpha. – mm201 Feb 16 '22 at 05:38