首页 > 解决方案 > 将颜色覆盖添加到 PNG 的非透明部分

问题描述

我正在尝试使用色轮,它会在不透明度为 50% 的 PNG 图像上添加叠加层,因此您仍然可以看到后面图像的轮廓。

我尝试过使用干预填充方法并在每个像素的基础上进行更改。

private function colorImage($url, $r = null, $g = null, $b = null) {

        $im = imagecreatefrompng($url);
        imageAlphaBlending($im, true);
        imageSaveAlpha($im, true);

        if (imageistruecolor($im)) {
            $sx = imagesx($im);
            $sy = imagesy($im);
            for ($x = 0; $x < $sx; $x++) {
                for ($y = 0; $y < $sy; $y++) {
                    $c = imagecolorat($im, $x, $y);
                    $a = $c & 0xFF000000;
                    $newColor = $a | $r << 16 | $g << 8 | $b;
                    imagesetpixel($im, $x, $y, $newColor);
                }
            }
        }

        ob_start();

        imagepng($im);
        imagedestroy($im);
        $image_data = ob_get_contents();

        ob_end_clean();

        $image_data_base64 = "data:image/png;base64," . base64_encode($image_data);

        return $image_data_base64;
}

之前:https ://imgur.com/v1xRixQ

当前:https ://imgur.com/67M9iCg

目标:https ://imgur.com/RxzaxTP

标签: phplaravelimage

解决方案


您可以使用干预图像图像库来执行此操作。

创建一个实例,该实例是一个填充了半透明 RGB 颜色的图像,使用源图像将其遮盖,然​​后将遮罩放在原始图像的顶部作为叠加层。

use Intervention\Image\ImageManager;

// setup
$red     = 255;
$green   = 0;
$blue    = 0;
$opacity = 0.25;

$manager = new ImageManager(['driver' => 'gd']);

// the source image
$image = $manager->make('./board.png');

// the fill color
$fill = $manager->canvas(
    $image->width(), 
    $image->height(), 
    [$red, $green, $blue, $opacity]
);

// use the source image to mask off only the portion of the fill that will be 
// used as the overlay
$fill->mask($image, true);

// apply the semi-transparent, masked fill to the source image
$image->insert($fill);

// render as a png
header('Content-Type: image/png');
echo $image->encode('png');

输出: https ://imgur.com/oIRP8Ir


推荐阅读