Color overlay on white PNG image with transparency

2019-08-30 11:45发布

I have the following image: http://i.stack.imgur.com/mM8cY.png

What I would like to do is create a "Color Overlay" effect like in Photoshop. I need some sort of code that will allow me to change each white pixels to the values specified in RGB numbers ranging from 0-255. I have heard about the ImageMagick class, but I could not find it anywhere, and I have no idea how to do it even with that class. I'm currently trying with imagefilter, but it doesn't work with white images. Here is my current code:

<?php
$match = array();
if (isset($_GET['c']) && preg_match('/^#?(?:[A-Fa-f0-9]{2}){3}$/',$_GET['c'],$match)){
    $match = str_split($match[0],2);
    foreach ($match as $k=>$m){ $match[$k] = intval($match[$k],16); }

    $img = imageCreateFromPng('splat.png');
    $background = imagecolorallocate($img, 0, 0, 0);
    imagecolortransparent($img, $background);
    imagealphablending($img, false);
    imagesavealpha($img, true);

    //Transformation code
    imagefilter($img, IMG_FILTER_COLORIZE, $match[0], $match[1], $match[2]);

    header('Content-type: image/png');
    imagePng($img);
    exit;
}
?>

1条回答
Rolldiameter
2楼-- · 2019-08-30 12:04

I found the solution. All I did was - using Photoshop - I added a red color overlay on the image, so now it looks like this: http://i.stack.imgur.com/mVARN.png

And then used the following PHP code:

<?php
$match = array();
$color = isset($_GET['c']) ? $_GET['c'] : false;
if ($color === false) isset($_GET['color']) ? $_GET['color'] : false;
$color = preg_replace('/^#/','',$color);
if (strlen($color) == 3) $color = $color[0].$color[0].$color[1].$color[1].$color[2].$color[2];
if (preg_match('/^(?:[A-Fa-f0-9]{2}){3}$/',$color,$match)){
    $match = str_split($match[0],2);
    foreach ($match as $k=>$m){ $match[$k] = intval($match[$k],16); }

    // Load image
    $img = imageCreateFromPng('splat.png');
    $background = imagecolorallocate($img, 0, 0, 0);
    imagecolortransparent($img, $background);
    imagealphablending($img, false);
    imagesavealpha($img, true);

    imagefilter($img, IMG_FILTER_COLORIZE, intval( intval($match[0],16) - 255 ,16), $match[1], $match[2]);

    header('Content-type: image/png');
    imagePng($img);
    exit;
}
?>

The key here is that I substracted the 255 red color value from input with this:

intval( intval($match[0],16) - 255 ,16)

and that changed the color properly.

查看更多
登录 后发表回答