Last active
March 2, 2021 01:46
-
-
Save oldmota/b64294f01034bdc43ecb6e75d8d95344 to your computer and use it in GitHub Desktop.
Python script to convert any file to PNG and back, made just for fun
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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