Skip to content

Instantly share code, notes, and snippets.

@DarkCat09
Last active March 30, 2022 11:35
Show Gist options
  • Save DarkCat09/b53a72d94786aed696372e889a3b7885 to your computer and use it in GitHub Desktop.
Save DarkCat09/b53a72d94786aed696372e889a3b7885 to your computer and use it in GitHub Desktop.
Convert your picture to a pixel art on forum code!
from PIL import Image
from typing import List, Tuple
scale = 28
def smallres(file:str) -> Image:
img = Image.open(file)
ratio = scale / max(img.size[0], img.size[1])
w = img.size[0] * ratio
h = img.size[1] * ratio
return img.resize((int(w),int(h)), Image.BILINEAR)
def pixels(pillowimg:Image) -> List[Tuple[int]]:
return list(pillowimg.getdata())
def hexcodes(size:Tuple[int], pixs:List[Tuple[int]]) -> List[List[str]]:
hex = []
w, h = size
for line in range(h):
arr = []
for pix in range(w):
r, g, b, *a = pixs[pix + line*w]
arr.append(f'#{r:02x}{g:02x}{b:02x}')
hex.append(arr)
return hex
def bbcode(img:str, scalef:int=28) -> str:
scale = scalef
small = smallres(img)
pxlst = pixels(small)
hxlst = hexcodes(small.size, pxlst)
bb = '[size=1]'
for line in hxlst:
for pix in line:
bb += f'[background={pix}][color={pix}]m.[/color][/background]'
bb += '\n'
bb += '[/size]'
return bb
if __name__ == '__main__':
myimg = '/storage/emulated/0/test.jpg'
with open('test.bb', 'wt') as f:
f.write(bbcode(myimg))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment