Skip to content

Instantly share code, notes, and snippets.

@natecraddock
Created August 6, 2016 01:37
Show Gist options
  • Save natecraddock/5c262af48a2eb4db0b0260419a5b6684 to your computer and use it in GitHub Desktop.
Save natecraddock/5c262af48a2eb4db0b0260419a5b6684 to your computer and use it in GitHub Desktop.
Inspired by a recent standupmaths video
# Nathan Craddock 2016
from PIL import Image
size = (256, 256)
num_pixels = size[0] * size[1]
# Returns the list of base 256 colors
def get_pixel_colors(n):
color_values = []
for i in reversed(range(num_pixels)):
m = n % pow(256, i)
if m != n:
color_values.append(n // pow(256, i))
n = m
else:
color_values.append(0)
return color_values
# Returns the number from a list of pixel colors
def get_number_from_pixels(n):
total = 0
for index, i in enumerate(reversed(range(num_pixels))):
total += n[i] * pow(256, index)
return total
# Open an image, and convert to a number
def open_image(path):
image = Image.open(path).convert('P')
pixels = image.load()
flattened = []
for y in range(image.size[1]):
for x in range(image.size[0]):
flattened.append(pixels[x, y])
return get_number_from_pixels(flattened)
# TODO: make this work for variable sizes
# Take a number, and save it as an image
def save_image(n, filename):
pattern = get_pixel_colors(n)
image = Image.new('P', size)
i = 0
pixels = image.load()
for y in range(image.size[1]):
for x in range(image.size[0]):
pixels[x, y] = pattern[i]
i += 1
image.save(filename + '.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment