convert image to byte literal in python

后端 未结 3 457
迷失自我
迷失自我 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:54

    I think you're just not printing out the data properly — there doesn't seem to be any need to mess around with base64 doing this.

    Here's proof:

    from itertools import izip
    import tempfile
    
    # 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
    
    # make a temp file from ICON data for testing
    _, ICON_PATH = tempfile.mkstemp()
    with open(ICON_PATH, 'wb') as icon_file:
        icon_file.write(ICON)
    
    # Convert raw data in the file into a valid Python string literal.
    
    # helper function
    def grouper(n, seq):
        "s -> (s0,s1,...sn-1), (sn,sn+1,...s2n-1), (s2n,s2n+1,...s3n-1), ..."
        for i in xrange(0, len(seq), n):
            yield seq[i:i+n]
    
    # read data file in binary mode
    a = open(ICON_PATH, 'rb').read()
    
    # create Python code to define string literal
    code = '\n'.join(['ICON2 = ('] +
                     ['    '+repr(group) for group in grouper(16, a)] +
                     [')'])
    
    print 'len(ICON): {}'.format(len(ICON))
    print 'len(a): {}'.format(len(a))
    print code
    exec(code)
    print
    print 'len(ICON2): {}'.format(len(ICON2))
    print 'ICON2 == ICON: {}'.format(ICON2 == ICON)
    

    Output:

    len(ICON): 1406
    len(a): 1406
    ICON2 = (
        '\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05'
        '\x00\x00\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00'
        '\x00\x00\x01\x00\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00'
        '\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00'
        '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
           ...
        '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
        '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
        '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff'
        '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
        '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
        '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
        '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    )
    
    len(ICON2): 1406
    ICON2 == ICON: True
    

提交回复
热议问题