Skip to content

Instantly share code, notes, and snippets.

@digarok
Created November 9, 2018 21:20
Show Gist options
  • Save digarok/fb232c0511d912de7e3e602749e68364 to your computer and use it in GitHub Desktop.
Save digarok/fb232c0511d912de7e3e602749e68364 to your computer and use it in GitHub Desktop.
Convert images to Apple II lores bytes to write directly to memory.
# Take some image and convert to LoRes bytes
# You should already have it in 16 Apple II colors
# but this will do a nearest color match if not.
from PIL import Image
from math import sqrt
img = Image.open("saved_Preview.BMP")
def distance3d((x1, y1, z1), (x2, y2, z2)):
return sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)
pixels = img.load() # create the pixel map
colors = [
(0,0,0), (0xDD,0,0x33), (0,0,0x99), (0xDD,0,0xDD),
(0,0x77,0), (0x55,0x55,0x55), (0x22,0x22,0xFF), (0x66,0xAA,0xFF),
(0x88,0x55,0x22), (0xFF,0x66,0), (0xAA,0xAA,0xAA), (0xFF,0x99,0x88),
(0,0xDD,0), (0xFF,0xFF,0), (0,0xFF,0x99), (0xFF,0xFF,0xFF)
]
bytes = []
for j in range(img.size[1]/2): # For every other row because we stack them into one GR byte
for i in range(img.size[0]/2): # for every other col because i'm taking an input image with doubled horizontal pixels
p1 = img.getpixel((i*2,j*2))
p2 = img.getpixel((i*2,(j*2)+1))
nearest_idx1 = colors.index(min(colors, key=lambda x: distance3d(x, p1)))
nearest_idx2 = colors.index(min(colors, key=lambda x: distance3d(x, p2)))
byte = nearest_idx1 + (nearest_idx2*16)
bytes.append(byte)
#img.show()
newFile = open("out.GR", "wb")
newFileByteArray = bytearray(bytes)
newFile.write(newFileByteArray)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment