php如何使图片下半部分看起来颜色更浅类似半透明
可以使用PHP的GD库来实现图片半透明效果,具体步骤如下:
- 打开图片并创建一个新的图像资源:
$srcImg = imagecreatefromjpeg('image.jpg');
$dstImg = imagecreatetruecolor(imagesx($srcImg), imagesy($srcImg));
- 将原图像复制到新的图像资源中:
imagecopy($dstImg, $srcImg, 0, 0, 0, 0, imagesx($srcImg), imagesy($srcImg));
- 设置半透明效果:
// 将下半部分的颜色值减少50%
for ($y = imagesy($dstImg) / 2; $y < imagesy($dstImg); $y++) {
for ($x = 0; $x < imagesx($dstImg); $x++) {
$color = imagecolorat($dstImg, $x, $y);
$alpha = ($color >> 24) & 0xFF;
$red = ($color >> 16) & 0xFF;
$green = ($color >> 8) & 0xFF;
$blue = $color & 0xFF;
$red = max(0, $red - 50);
$green = max(0, $green - 50);
$blue = max(0, $blue - 50);
$color = imagecolorallocatealpha($dstImg, $red, $green, $blue, $alpha);
imagesetpixel($dstImg, $x, $y, $color);
}
}
// 设置透明度
imagealphablending($dstImg, false);
imagesavealpha($dstImg, true);
- 输出图像:
header('Content-type: image/jpeg');
imagejpeg($dstImg);
完整代码如下:
$srcImg = imagecreatefromjpeg('image.jpg');
$dstImg = imagecreatetruecolor(imagesx($srcImg), imagesy($srcImg));
imagecopy($dstImg, $srcImg, 0, 0, 0, 0, imagesx($srcImg), imagesy($srcImg));
for ($y = imagesy($dstImg) / 2; $y < imagesy($dstImg); $y++) {
for ($x = 0; $x < imagesx($dstImg); $x++) {
$color = imagecolorat($dstImg, $x, $y);
$alpha = ($color >> 24) & 0xFF;
$red = ($color >> 16) & 0xFF;
$green = ($color >> 8) & 0xFF;
$blue = $color & 0xFF;
$red = max(0, $red - 50);
$green = max(0, $green - 50);
$blue = max(0, $blue - 50);
$color = imagecolorallocatealpha($dstImg, $red, $green, $blue, $alpha);
imagesetpixel($dstImg, $x, $y, $color);
}
}
imagealphablending($dstImg, false);
imagesavealpha($dstImg, true);
header('Content-type: image/jpeg');
imagejpeg($dstImg);
``
原文地址: https://www.cveoy.top/t/topic/c8q3 著作权归作者所有。请勿转载和采集!