Generate palette from image

I want to automatically generate a palette from an image.

Something like this, where the output is an image a single pixel tall, and 256 pixels wide, from all the colors of an input image.

enter image description here

I’ve tried Photoshop, where you can generate the palette, but it only supports exporting in .act and .pal files, which don’t work for me.

The palette should be 256 colors, which the source image already is in.

I could do it manually, but it would take forever. Googling isn’t helping me, but I thought there’s bound to be someone that knows of a script or a way to do this.

I looked at this question, but the command doesn’t work for me (Windows) and even if it did, I would still need a way to generate the actual png file from the text file it outputs.

Thanks in advance!

Also, I wasn’t sure where to put this, so I hope this is the correct site. Feel free to delete it if it’s not.

Edit: A way to convert an .act or .pal file to an actual image works as well. I couldn’t find any way to do this either.

Answer

Some basic Python knowledge and a quick look at pyPNG Code Examples quickly lead to this:

import png
import sys

def makeRamp (input_name, output_name):
    source = png.Reader(input_name)
    width, height, pixels, metadata = source.read()

    if metadata['bitdepth'] == 8 and metadata['planes'] == 1 and 'palette' in metadata:
        print ('processing 8-bit indexed image')

        pal_img = open(output_name, 'wb')      # binary mode is important
        w = png.Writer(256, 1, palette=metadata['palette'])
        w.write(pal_img, [range(256)])
        pal_img.close()
    else:
        print ('this is not an 8-bit indexed image!')

if len(sys.argv) == 3:
    makeRamp (sys.argv[1], sys.argv[2])
else:
    print("please supply an input and a destination name")

All heavy lifting is done by the PNG library; as you see, it needs only minor knowledge of the (very intricate) internal file format of PNGs. (Stuff like, you have to know that you must check the color bit depth – this program will reject non-indexed color images!)

A test run on this 8-bit indexed image:

a sample PNG image taken from another question

python scratch.py 7vnEt.png ramp.png

yields the result

processing 8-bit indexed image

and a new image file “ramp.png” that looks like this:

color ramp for above image

Zoomed in x8 on the start:

zoomed in color ramp

Attribution
Source : Link , Question Author : zirr , Answer Author : Jongware

Leave a Comment