php - 将颜色覆盖添加到 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;
}
解决方案
您可以使用干预图像图像库来执行此操作。
创建一个实例,该实例是一个填充了半透明 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');
推荐阅读
- linux-kernel - 如何编写USB存储设备驱动程序
- amazon-web-services - AWS 配置文件似乎没有配置!无服务器框架错误?
- php - 凭据无效 - Google Drive API
- php - 如何使用日期和时间 ACF 字段根据是否经过时间来隐藏 the_content()
- python-3.x - 使用 tinymce 的 Python 图像上传处理程序代码
- c# - 将 Db 查询结果划分为任意数量的任务
- ios - 为什么 iPhone 12 Pro 立体视频帧垂直移位?
- java - 是否可以在 Cloudsim 中计算动态阈值?
- c# - 第三者名单变更通知
- primefaces - 尽管在 primefaces p:cellEditor 中具有相同的表达式,但 h:outputText 中的 JSF2 ValueExpression 不会评估为 true