How To

Little python script to convert images to sprites ;-)

6

Greenpilloz 2020-11-04 16:25

Hi there, heres a little piece of code to convert png images into sprites for LowRes NX:



#!/usr/bin/env python3
"""
Little script to convert pngs (or any image type) to tilemap
in the lowres nx format

If the image is too long
we produce many character sets
in several ROMS

If the image is wider than 16*8, it will be cropped

We cut 8x8 images and convert them to 4 colors

Made by @Greenpilloz, no licence (Do what you want)

"""
from PIL import Image
import sys


def convert(infile = 'tileset_16x16_Jerom_CC-BY-SA-3.0.png'):
    img = Image.open(infile)
    i=0
    j=0
    MAXROMS = 7
    ROM=2
    lines = ['#2:MAIN CHARACTERS']
    for j in range(0, img.size[1], 8):

        # if the image is too long
        # we produce many character sets
        # in several ROMS
        if j>0 and j % (16*8) == 0:
            ROM += 1
            lines.append('\n\n#'+str(ROM)+':OTHER CHARS '+str(ROM-2))


        # If the image is wider than 16*8, it will be cropped
        for i in range(0, min(16*8,img.size[0]), 8):

            # We cut a 8x8 image and convert it to 4 colors
            im = img.crop((i, j, i+8, j+8))
            result = im.convert('P', palette=Image.ADAPTIVE, colors=4)
            pix = result.load()

            ss0=''
            ss1=''
            for y in range(0, 8):
                s0 = ''
                s1 = ''
                for x in reversed(range(0, 8)):
                    b0 = bin(256+round((pix[x,y])))[-1]
                    b1 = bin(256+round((pix[x,y])))[-2]
                    #print(pix[i,j], b1)
                    s0=b0+s0
                    s1=b1+s1
                s0 = ("%02X" % int(s0,2))
                s1 = ("%02X" % int(s1,2))
                ss0=ss0+s0
                ss1=ss1+s1

                if len(ss0)==16:
                    lines.append(ss0+ss1)
                    ss0=''
                    ss1=''
        if ROM >= MAXROMS:
            break

    # writting to a files
    with open('out.nx', 'w') as f:
        f.writelines('\n'.join(lines))

if __name__ == '__main__':
    if len(sys.argv) > 1:
        for file in sys.argv[1:]:
            convert(file)
    else:
        convert()

To make it work you need:

I did a test with the file attach in the screenshot, and that looks prety promising. This image was taken from [https://opengameart.org/content/16x16-fantasy-tileset]

Enjoy ;-)

out.nx | Open in app
2020-11-04 16:25

G-9 2020-11-05 06:17

OMG WHAT THIS IS SO BEAUTIFUL THANK U THANK U THANK U x10000
(This was exactly what i was looking for)


G-9 2020-11-05 06:20 (Edited)

Authorise the script to be executed (type chmod 777 convert2nx.png in a terminal on mac or linux)

Also works because 7 means read-write-exec
So 777 means read write exec for you, rwx for others in the same group and rwx for all others


Log in to reply.