Search code examples
pythonpython-imaging-librarypng

Python to convert data to a png file


We have an intranet/knowledge base site that has an API. I can use that API to pull assets from the backend. That worked as expected... except... I'm not sure what format the return is in. The file is a png file, and it has the png chunks listed like IHDR but can I just convert this (see below) to base64 and push it through PIL or some other renderer to get it to output (I am on a Mac)? Thanks.

�PNG

IHDR�
�AMA��
  �a��IDATx^��Ǚ�?;�3�����
                         ;���$ffK�,�-ɒAff��c;�c�cf
]r��]r����oO�Z��+Y���g����S�VuOO�t��٪�ѧ3�QO�
                                         �5c}
��\$&�*��&^M�,�u*}5��� 2� �O���b�O#����|6?��R-
                                          ۏÑ0���    `G؂�,�&&h�+Bb�ĤH�/!�+���
*�F�Ѫe��=T--���F'���}��L�q�'��Q��bxQo�u�DL�Um�H�-��E�����N���ڝY1H8�u���         
���K�P��K�ma/.�-O Wj
                                                                   
x�<N�n�ȅ~�ƣW�c���i��]z�I%���ɠ��N��2}���C��7lѷF}. 
�����z�Z���v�j�B�B��y��N��m4h$"��H$"G�a2>_'��r��f�\'��
�BjQ˂�^&
    �MA�!�eC���B>h�$�:�C���L�}�XġUW�i�pG{_k�#�鬶gR�/��m(�,�L���(�q{��b<ڑ�zL�V�6�]]*�K� 
)����6��Sa�B쳘|s*,Ǔ��"��ժ�R��^+��W��yv��wg�w|����3�]3���^�x���V�x�ꗮ\����߽c�{w�~��-? 
�����?��]{޼�������;޽�ܺn��έ;`����s�v��n�����^�n
                                                                                     
��뷽q���o<獛��}����|��z���/�r��[��z�O�|�����wz�{�}���_~��w^��K/������w���_�x�������|. 
�޿���/�y

Solution

  • Updated Answer

    Actually, if you just want to save it to disk, without decompressing it into a PIL Image, there is no need for PIL, you can just do:

    with open('result.png', 'wb') as fd:
        fd.write(YOUR_API_VALUE)
    

    Original Answer

    To save the image as a PNG, or potentially a JPEG/TIFF/GIF:

    from io import BytesIO
    from PIL import Image
    
    im = Image.open(BytesIO(YOUR_API_VALUE))
    im.save('image.png')
    

    and vary the extension according to the format you want.


    To view the image:

    from io import BytesIO
    from PIL import Image
    
    im = Image.open(BytesIO(YOUR_API_VALUE))
    im.show()