Reputation: 357
Given an image file, what's the best way to convert it to the old school 16 colors? i.e. white, orange, magenta, light blue, yellow, lime, pink, gray, light gray, cyan, purple, blue, brown, green, red, and black.
I've made a little 1x16 pixel image containing all 16 of those colors that I can use as a source palette (right?) but I'm having trouble making use of it. It seems like imagepalettecopy()
is what I want (take the 16 pixel data image's color palette and copy it onto a fresh image) but the code I came up with isn't working:
<?php
$palette = imagecreatefrompng( __DIR__ . '/palette.png' );
$source = imagecreatefromjpeg( __DIR__ . '/testimage.jpg' );
$source_w = imagesx( $source );
$source_h = imagesy( $source );
$image = imagecreate( $source_w, $source_h );
imagepalettecopy( $palette, $image );
imagecopy( $image, $source, 0, 0, 0, 0, $source_w, $source_h );
header('Content-Type: image/png');
imagepng( $image );
It seems to just convert it to 16 colors of it's choosing or something (I'm not quite sure).
What am I missing or doing wrong?
EDIT: My imagepalettecopy()
call is backwards but fixing it doesn't help either. See below comments.
Upvotes: 4
Views: 1545
Reputation: 264
Does changing
imagepalettecopy($palette, $image);
into
imagepalettecopy($image, $palette);
work?
EDIT:
I tried the following palette as a gif:
I think these colors are different from yours. (I hand picked the greens from the picture...)
This is the code I tried (not really a difference here):
<?php
$palette = imagecreatefromgif('palette-gif-03.gif');
$source = imagecreatefromjpeg('test-image-01.jpg');
$source_w = imagesx($source);
$source_h = imagesy($source);
$image = imagecreate($source_w, $source_h);
imagepalettecopy($image, $palette);
imagecopy($image, $source, 0, 0, 0, 0, $source_w, $source_h);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($imgage);
imagedestroy($palette);
imagedestroy($source);
?>
And this was my result:
Please let me know if I should delete the picture?!!
Upvotes: 1