convert image to byte literal in python

后端 未结 3 421
迷失自我
迷失自我 2021-01-22 21:13

I\'m trying to store an image as text, so that I can do something like this example of a transparent icon for a Tk gui:

import tempfile

# byte literal code for          


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-22 21:48

    Well I did figure out you can do it this way:

    import tempfile, base64, io
    
    # byte literal code for a transparent icon, I think
    ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00'
            b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00'
            b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
            b'\x00\x01\x00\x00\x00\x01') + b'\x00'*1282 + b'\xff'*64
    
    # makes a temp file for the transparent icon and saves it
    _, ICON_PATH = tempfile.mkstemp()
    with open(ICON_PATH, 'wb') as icon_file:
        icon_file.write(ICON)
    
    with open(ICON_PATH, 'rb') as imgFile:
        a = imgFile.read()
    
    b = base64.b64encode(a)
    
    print b # output does not match what ICON equals above
    
    with open('test.png','wb') as writeFile:
        writeFile.write(b.decode('base64'))
    

    but I still want to know how to get the same format as 'ICON = (...' at the top

提交回复
热议问题