User:Psychonaut/palette.sh

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
#!/bin/bash

# Name   : palette.sh
# Author : Psychonaut
# Date   : 2007-11-16
# Licence: public domain
# Purpose: This bash script generates an SVG image of a uniform RGB palette
# Usage  : Modify the variables in the "User-modifiable variables" section
#          to taste; then run the script.  The SVG image is sent to
#          standard output.

# User-modifiable variables
rbits=2                       # Number of bits for red
gbits=2                       # Number of bits for green
bbits=2                       # Number of bits for blue
cols=8                        # Number of columns in grid
gridsize=64                   # Width of each grid square
cellsize=60                   # Width of each cell within a grid square
strokewidth=4                 # Stroke width
strokecolor="black"           # Stroke colour

# Dependent variables
rvals=$(( 2 ** rbits ))
gvals=$(( 2 ** gbits ))
bvals=$(( 2 ** bbits ))
rows=$(( rvals * gvals * bvals / cols ))

cat <<EOF
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg"
     version="1.0"
     width="$(( cols * gridsize ))"
     height="$(( rows * gridsize ))">
EOF

row=0
col=0
for (( r = 0; r < rvals; r++ ))
  do
  for (( g = 0; g < gvals; g++ ))
    do
    for (( b = 0; b < bvals; b++ ))
      do
      cat <<EOF
      <rect width="$cellsize"
            height="$cellsize" 
            y="$((row * gridsize + (gridsize - cellsize) / 2))"
            x="$((col * gridsize + (gridsize - cellsize) / 2))" 
            style="fill:rgb($((255 * r / (rvals-1))),$((255 * g / (gvals-1))),$((255 * b / (bvals-1))));
                   stroke-width:$strokewidth;
                   stroke:$strokecolor;" />
EOF
      if ((++col == cols))
      then
        col=0
        ((row++))
      fi
    done
  done
done

cat <<EOF
</svg>
EOF