Blend transparent gradient with an image using php GD library

ぃ、小莉子 提交于 2019-12-06 07:56:39

If you create a image using imagecreatetruecolor it gets a black background. Using imagefill you can change the background of an image easily. The imagecolorallocatealpha function let's you create a color containing transparency. 127 means fully transparent and 0 not transparent.

It works now and I simplified your code a bit:

function hex2rgb($hex) {
    $rgb[0] = hexdec(substr($hex, 0, 2));
    $rgb[1] = hexdec(substr($hex, 2, 2));
    $rgb[2] = hexdec(substr($hex, 4, 2));
    return $rgb;
}

if (isset($_GET['start']) && isset($_GET['stop']) && isset($_GET['color'])) {
    $color = hex2rgb($_GET['color']);
    $range = $_GET['stop']-$_GET['start'];

    // create input image
    $input = imagecreatefrompng('file.png');


    // create output image
    $height = imagesy($input);
    $width = imagesx($input);
    $output = imagecreatetruecolor($width, $height);

    // put a transparent background on it
    $trans_colour = imagecolorallocatealpha($output, 0, 0, 0, 127);
    imagefill($output, 0, 0, $trans_colour);

    // create the gradient
    for ($x=0; $x < $width; ++$x) {
        $alpha = $x <= $_GET['start'] ? 0 : round(min(($x - $_GET['start'])/$range, 1)*127);
        $new_color = imagecolorallocatealpha($output, $color[0], $color[1], $color[2], $alpha);
        imageline($output, $x, $height, $x, 0, $new_color);
    }

    // copy the gradient onto the input image
    imagecopyresampled($input, $output, 0, 0, 0, 0, $width, $height, $width, $height);

    // output the result
    header('Content-Type: image/png');
    imagepng($input);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!