PHP GIF / PNG True Colorize Filter that preserves brightness and alpha

I’ve been working on a script for some time now to change the colors of GIF and PNG files that work better than the PHP coloring filter, which does not preserve brightness. I came up with this, but this is not entirely correct:

$filename = "images/sprites/".$_GET['sprite'].".png";
    $im = imagecreatefrompng($filename);
    $nim = imagecreate( imagesx($im), imagesy($im) );
    $background = imagecolorallocate($nim, 255, 0, 255);

    $size = getimagesize($filename);

    for($y = 0; $y < imagesy($nim); $y++) {
        for($x = 0; $x < imagesx($nim); $x++) {
            $rgb = imagecolorat($im, $x, $y);
            $colors = imagecolorsforindex($im, $rgb);
            $mods = explode("x",$_GET['color']);

            $colors['red']   = ($colors['red'] / 8 + (255 - ((255 - $mods[0] - $colors['red']) * 2))) / 2;
            $colors['green'] = ($colors['red'] / 8 + (255 - ((255 - $mods[1] - $colors['green']) * 2))) / 2;
            $colors['blue']  = ($colors['red'] / 8 + (255 - ((255 - $mods[2] - $colors['blue']) * 2))) / 2;

            $r = $colors['red'];
            $g = $colors['green'];
            $b = $colors['blue'];

            if($r < 0) $r = 0;
            if($g < 0) $g = 0;
            if($b < 0) $b = 0;
            if($r > 255) $r = 255;
            if($g > 255) $g = 255;
            if($b > 255) $b = 255;

            if(!isset($color[$r.$g.$b])) {
                $color[$r.$g.$b] = imagecolorallocate($nim, $r, $g, $b);
            }

            imagesetpixel($nim, $x, $y, $color[$r.$g.$b]);
        }
    }

    imagecolortransparent($nim, 1);
    header('Content-Type: image/png');
    imagepng($nim);
+3
source share
2 answers

Looks like you want tinted shades of gray. It supports transparency ...

http://www.exorithm.com/algorithm/view/duotone_image

+4
source

Try these functions after $im = imagecreatefrompng($filename);

imagealphablending($im, false);
imagesavealpha($im, true);

And use imagecreatetruecolor ():

$nim = imagecreatetruecolor ( imagesx($im), imagesy($im) );
-1
source

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


All Articles