################################################################################
# Copyright (c) 2010-2019 Trimble Inc.
# $Id: create_png_via_python.py,v 1.2 2019/09/11 00:50:54 ddelore Exp $
################################################################################
#
# create_png_via_python
#
# Simple script to convert a PNG file (or any binary file) into ASCII data.
# The data is saved into a format that can be loaded directly into Python.
# Python code is also generated that can be used to write the ASCII data back
# out to recreate the file.
# Used to embed binary data (images etc.) into Python executables.
#
################################################################################

import sys

# Check the command line
if ( len( sys.argv ) != 2 ) :
  print "Expected command is:"
  print " python create_python_image.py <PNG file>"
  sys.exit()

# Open and read the data file
png_name = sys.argv[1]
fpng = open( png_name, 'rb' )
png = fpng.read()
fpng.close()

# Save 25 bytes per line
# Compute how many lines are needed
len25 = int( len( png ) / 25 )

# Convert the binary data into ASCII
for y in range( len25+1 ) :
  # Line start
  if ( y == 0 ) :
    str_out = 'png = ( \''
  else :
    str_out = '    +   \''

  # Compute bytes on line
  if ( y == len25 ) :
    max_x = len( png ) - ( len25 * 25 )
  else :
    max_x = 25

  # Generate line of data
  for x in range( max_x ) :
    # Convert byte to hex value in ASCII
    tmp_hex = hex(int(ord( png[(y*25) + x] )))

    # Append to string, zero padding as needed
    if ( len( tmp_hex ) == 3 ) :
      str_out = str_out + '0' + tmp_hex[2:3]
    else :
      str_out = str_out + tmp_hex[2:4]

  # Terminate the line
  print str_out + '\''

# Terminate the data string
print '    )'

# Generate some Python code to convert the data back into
# a binary file
print 'fptr = open( \'' + png_name + '\', \'wb\' )'
print 'for x in range( ' + str( len( png ) ) + ' ) :'
print '  tmpc = chr( int( png[ 2*x : 2*x+2 ], 16 ) )'
print '  fptr.write( tmpc )'
print 'fptr.close()'
