Convert image to predefined 16 colors

Given the image of the file, what's the best way to convert it to an old school of 16 colors? that is, white, orange, purple, cyan, yellow, lime, pink, gray, light gray, cyan, violet, blue, brown, green, red, and black.

I made a small 1x16 image containing all 16 of these colors that I can use as the original palette (right?), But I had problems using it. It seems that imagepalettecopy() is what I want (take the 16-pixel color palette of the images and copy it to the new image), but the code I came up with does not work:

 <?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 he just converts it into 16 colors, which he chooses or something (I'm not quite sure).

What am I missing or is something wrong?

EDIT: My call to imagepalettecopy() reverse, but the fix does not help. See comments below.

+4
source share
1 answer

Does the change change imagepalettecopy ($ palette, $ image);
in
imagepalettecopy ($ image, $ palette);
Job?

EDIT:

I tried the following palette as a gif:

enter image description here

I think these colors are different from yours. (I took the greens from the picture ...)

This is the code I tried (actually this is not a difference):

 <?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 that was my result:

enter image description here

Please let me know if I have to delete the image? !!

+1
source

Source: https://habr.com/ru/post/1480871/


All Articles