imagecopyresampled具有不透明度

时间:2014-08-23 06:19:16

标签: php transparent

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

我正在使用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中使用?

2 个答案:

答案 0 :(得分:3)

只需使用这个简单的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

答案 1 :(得分:2)

尝试使用这个开源PHP项目:

Image workshop https://github.com/Sybio/ImageWorkshop

相关问题