Title: Palette-loading utility function

Author: Kevin Turner (acapnotic at users.sourceforge.net)
Submission date: May 29, 2001

Description: Loads a palette file and returns a list suitable for Surface.setpalette()

Download: loadpal.py

pygame version required: Any
SDL version required: Any
Python version required: Any

Comments: If you've ever tried to specify a surface's entire palette using surface.set_palette(), you may have noticed how frustrating it is to create 256 individual RGB tuples. Kevin's code allows you to load a gimp or Fractint palette file by calling load_palette(filename), or you can specify your own palette file in the format indicated in the docstrings.

Messages: 0


# Palette-loading utility function, by Kevin.
# Public domain.  Have fun.

import re

def load_palette(name='Firecode'):
    """Loads a palette file and returns a list suitable for Surface.setpalette()

    Loads a palette file, which is anything that looks like this:

    0 0 0
    0 0  4
    0 64 8
    ...

    GIMP and Fractint palette files both match this description.
    Lines that don't match are silently ignored.
    Only recognizes decimal values, not 0xFF or #AA66FF.
    """

    f = open(name)
    pal = []
    rgb_re = re.compile('^(?:\s+)?(\d+)\s+(\d+)\s+(\d+)')
    for l in f.readlines():
        m = rgb_re.search(l)
        if m:
            pal.append(tuple(map(int,m.groups())))

    if len(pal) != 256:
        print "Warning: palette \'%s\' does not contain 256 entries." % name
    if pal[0] != (0,0,0):
        print "Warning: palette \'%s\' has entry 0 set to non-black color"\
              % name, pal[0]
    return pal

Main - Repository - Submit - News

Feedback