Mega Code Archive

 
Categories / C / Small Application
 

Generate a color palette

#include <stdio.h> #include <error.h> #include <math.h> #include <gd.h> #define RGB2INT(r,g,b) (b + 256 * g + 256 * 256 * r) int main(int argc, char *argv[]) { FILE *fp = {0}; gdImagePtr img = {0}; char *fname = NULL; int x, y, w, h, color; int red, green, blue; int palette[256] = {0}; if(argc != 2) error(1, 0, "Usage: gdpalette image.png"); else fname = argv[1]; w = 256, h = 100; img = gdImageCreateTrueColor(w, h); for(x = 0; x < 256; x++) { red = (int)(128.0 + 128 * sin(3.1415 * x / 16.0)); green = (int)(128.0 + 128 * sin(3.1415 * x / 32.0)); blue = (int)(128.0 + 128 * sin(3.1415 * x / 64.0)); palette[x] = RGB2INT(red, green, blue); } for(x = 0; x < w; x++) for(y = 0; y < h; y++) { red = gdImageRed(img, palette[x]); green = gdImageGreen(img, palette[x]); blue = gdImageBlue(img, palette[x]); color = gdImageColorAllocate(img, red, green, blue); gdImageSetPixel(img, x, y, color); } if((fp = fopen(fname, "w")) == NULL) error(1, 0, "Error - fopen(): %s", fname); else { gdImagePng(img, fp); fclose(fp); } gdImageDestroy(img); return 0; }