2013-07-27 183 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

我很高興它幫助你! –