2013-07-27 176 views
0

我有一小段代码,PHP图片不能让背景透明

它的想法是创建一个透明画布,以定义的高度/宽度,所以我能够把无论是JPG/png/gif在那里。

但是,如果它放置一个PNG在那里与透明度,它需要保持它的透明度。

这是代码

header("Content-type: image/png"); 

    $canvas = imagecreatetruecolor($maxWidth, $maxHeight); 
    $image = $_GET['file']; 
    $leftOffset = ($maxWidth/2) - ($width/2); 
    $topOffset = ($maxHeight/2) - ($height/2); 
    $quality = (isset($_GET['quality'])) ? (int) ceil($_GET['quality']/10) : ceil($DEFAULT_QUALITY/10); 

    $quality = $quality == 10 ? 9 : $quality; 

    switch($mime){ 
     case "image/jpeg": 
      $image = imagecreatefromjpeg($image); 
      $red = imagecolorallocate($canvas, 0, 255, 0); 
      imagecolortransparent($canvas, $red); 
      imagefill($canvas, 0, 0 ,$red); 
     break; 
     case "image/gif": 
      $image = imagecreatefromgif($image); 
     break; 
     case "image/png": 
      $background = imagecolorallocate($canvas, 255, 0, 0); 
      imagecolortransparent($canvas, $background); 
      imagealphablending($canvas, false); 
      imagesavealpha($canvas, true); 
      $image = imagecreatefrompng($image); 
     break; 
    } 

    imagecopyresampled($canvas, $image, $leftOffset, $topOffset, 0, 0, $width, $height, $width, $width); 
    imagepng($canvas, null, $quality); 
    imagedestroy($canvas); 

然而问题是样品,画布保持黑色,而图像周围的框区域是透明的。

下面的图片说明了这一点,石灰绿颜色是人体{背景:石灰;}这样你就能够看到透明区域

enter image description here

我试图用一个透明的颜色后, imagecreatetruecolor

$red = imagecolorallocate($canvas, 255, 0, 0); 
imagecolortransparent($canvas, $red); 
imagefill($canvas, 0, 0 ,$red); 

如果巴纽有淡入淡出效果,它得到它周围的讨厌的红光,其中的颜色不再是恰好255,0,0

有什么建议吗?

谢谢

+0

你见过我的答案吗? –

回答

0

这应该适合你!

<? 
$image = "your_image.png"; 

$image_info = getimagesize($image); 
$width = $image_info[0]; 
$height = $image_info[1]; 
$mime_type = $image_info["mime"]; 
$maxWidth = 250; 
$maxHeight = 250; 
$quality = 9; 

header("Content-type: $mime_type"); 

$canvas = imagecreatetruecolor($maxWidth, $maxHeight); 
imagealphablending($canvas, false); 
$background = imagecolorallocatealpha($canvas, 255, 255, 255, 127); 
imagefilledrectangle($canvas, 0, 0, $maxWidth, $maxHeight, $background); 
imagealphablending($canvas, true); 

$leftOffset = ($maxWidth/2) - ($width/2); 
$topOffset = ($maxHeight/2) - ($height/2); 

switch($mime_type) 
{ 
    case "image/jpeg": 
     //JPG code 
     break; 
    case "image/gif": 
     //GIF code 
     break; 
    case "image/png": 
     $new_image = imagecreatefrompng($image); 
     imagecopyresampled($canvas, $new_image, $leftOffset, $topOffset, 0, 0, $width, $height, $width, $height); 
     imagealphablending($canvas, true);   
     imagesavealpha($canvas, true); 
     imagepng($canvas, null, $quality); 
     imagedestroy($canvas);   
     break; 
} 
?> 
+0

不错的一个家伙,一直在寻找这个解决方案一个小时。 –

+0

我很高兴它帮助你! –