Skip to content

Instantly share code, notes, and snippets.

@requeijaum
Forked from oldmota/file_to_png.py
Created March 2, 2021 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save requeijaum/623127ff04dec6b382ef9c32c558e5ed to your computer and use it in GitHub Desktop.
Save requeijaum/623127ff04dec6b382ef9c32c558e5ed to your computer and use it in GitHub Desktop.
Python script to convert any file to PNG and back, made just for fun
from sys import argv
from math import sqrt, ceil
from struct import pack, unpack
from PIL import Image
def file_to_image(data, ext):
size = pack(">I", len(data))
full_data = bytearray(ext + '\0', 'ascii') + size + data
while len(full_data) % 4 != 0:
full_data += bytearray('\0', 'ascii')
width = ceil(sqrt(len(full_data) / 4))
img_dest = Image.new('RGBA', (width, width))
pixels = img_dest.load()
for i in range(width):
for j in range(width):
pos = (i*width + j)*4
if pos < len(full_data):
pixels[j,i] = (full_data[pos], full_data[pos+1],
full_data[pos+2], full_data[pos+3])
else:
pixels[j,i] = (0, 0, 0, 0)
return img_dest
def image_to_file(img):
pixels = img.load()
data = bytearray()
for i in range(img.width):
for j in range(img.width):
data.extend(pixels[j,i])
ext = bytearray()
byte = 0
while byte < len(data) and data[byte] != 0:
ext.append(data[byte])
byte += 1
ext = ext.decode('ascii')
byte += 1
size = unpack('>I', data[byte:byte+4])[0]
byte += 4
data = data[byte:byte+size]
return data, ext
if len(argv) == 2:
name = '.'.join(argv[1].split('.')[:-1])
ext = argv[1].split('.')[-1]
if ext == 'png':
img = Image.open(argv[1])
data, ext = image_to_file(img)
with open(name + '_.' + ext, mode='wb') as file:
file.write(data)
else:
with open(argv[1], mode='rb') as file:
fileContent = file.read()
img = file_to_image(fileContent, ext)
img.save(name + '.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment