gpt4 book ai didi

php - imagecopyresampled 不透明度

转载 作者:可可西里 更新时间:2023-11-01 00:44:02 25 4
gpt4 key购买 nike

我想在另一个大图像上添加一个小图像作为不透明的水印。

我正在使用 imagecopyresampled 将图像放在另一个图像上。

但是,如何为水印图像提供不透明度。

请帮帮我。

我正在使用这个简单的示例代码在没有不透明度的图像上添加水印:

<?php

$background = imagecreatefrompng("background.png");

if ($background !== false) {
$watermark = imagecreatefrompng("watermark.png");
// Add watermark on background
imagecopyresampled($background,$watermark,
100, 100, 0, 0,
128, 128, 128, 128);
// Add image header
header("Content-type: image/png");
imagepng($background);
imagedestroy($background);
}

例如:

这是背景图或主图

This is background or main image

这是水印图

enter image description here

我想要这种类型的输出

enter image description here

在 PHP 中是否可行?

最佳答案

只需使用这个简单的 PHP 函数:

<?php

function filter_opacity(&$img, $opacity) //params: image resource id, opacity in percentage (eg. 80)
{
if (!isset($opacity)) {
return false;
}
$opacity /= 100;

//get image width and height
$w = imagesx($img);
$h = imagesy($img);

//turn alpha blending off
imagealphablending($img, false);

//find the most opaque pixel in the image (the one with the smallest alpha value)
$minalpha = 127;
for ($x = 0; $x < $w; $x++) {
for ($y = 0; $y < $h; $y++) {
$alpha = (imagecolorat($img, $x, $y) >> 24) & 0xFF;
if ($alpha < $minalpha) {
$minalpha = $alpha;
}
}
}

//loop through image pixels and modify alpha for each
for ($x = 0; $x < $w; $x++) {
for ($y = 0; $y < $h; $y++) {
//get current alpha value (represents the TANSPARENCY!)
$colorxy = imagecolorat($img, $x, $y);
$alpha = ($colorxy >> 24) & 0xFF;
//calculate new alpha
if ($minalpha !== 127) {
$alpha = 127 + 127 * $opacity * ($alpha - 127) / (127 - $minalpha);
} else {
$alpha += 127 * $opacity;
}
//get the color index with new alpha
$alphacolorxy = imagecolorallocatealpha($img, ($colorxy >> 16) & 0xFF, ($colorxy >> 8) & 0xFF, $colorxy & 0xFF, $alpha);
//set pixel with the new color + opacity
if (!imagesetpixel($img, $x, $y, $alphacolorxy)) {
return false;
}
}
}

return true;
}

使用示例:

<?php
$image = imagecreatefrompng("img.png");
filter_opacity($image, 75);
header("content-type: image/png");
imagepng($image);
imagedestroy($image);

来源:http://php.net/manual/en/function.imagefilter.php

关于php - imagecopyresampled 不透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25459046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com