1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| <?php
header( "content-type: image/png" );
$img_url = $_GET['img'];
$opacity = ( is_numeric($_GET['opacity']) && $_GET['opacity']>=0 && $_GET['opacity']<=100 )? intval($_GET['opacity']) : 100;
$image = filter_opacity( $img_url, $opacity );
imagepng( $image );
imagedestroy( $image );
// -------------------
function filter_opacity( $img_url, $opacity ) //params: image URL, opacity in percentage (eg. 80)
{
if( !isset( $opacity ) )
{ return false; }
$opacity /= 100;
$extension = strtolower(pathinfo($img_url, PATHINFO_EXTENSION));
if( $extension == 'png' )
{
$img = imagecreatefrompng( $img_url );
}
elseif( in_array($extension, ['jpg','jpeg']) )
{
imagepng(imagecreatefromstring(file_get_contents($img_url)), "output.png");
$img = imagecreatefrompng( "output.png" );
} else {
return false;
}
//get image width and height
$w = imagesx( $img );
$h = imagesy( $img );
imagesavealpha($img, true);
//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 $img;
}
// ------------------- |
Partager