Reputation: 15548
I want to add a small image on anther big image as a watermark with opacity.
I'm using imagecopyresampled
to put image on anther image.
But, how to provide opacity for watermark image.
Please help me.
I'm using this simple example code for add watermark on image without opacity:
<?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);
}
For example:
This is background or main image
This is watermark image
I want this type of output
Is it possible or not in PHP?
Upvotes: 3
Views: 1785
Reputation: 1485
Try to use this opensource PHP project:
Image workshop https://github.com/Sybio/ImageWorkshop
Upvotes: 2
Reputation:
Just use this simple PHP function:
<?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;
}
Example of usage:
<?php
$image = imagecreatefrompng("img.png");
filter_opacity($image, 75);
header("content-type: image/png");
imagepng($image);
imagedestroy($image);
Source: http://php.net/manual/en/function.imagefilter.php
Upvotes: 3