2010-09-19 77 views
1

我使用這個代碼:如何保留透明度在PHP GD上PNG

<?php 
list($width, $height, $type, $attr) = getimagesize("terrain.png"); 
    $canvas = imagecreatetruecolor($width, $height); 


$src = imagecreatefrompng("terrain.png"); 
if($_GET['glass'] == 1){ 
$src2 = imagecreatefrompng("rock.png"); 
} 

imagecopymerge($canvas, $src, 0, 0, 0, 0, $width, $height, 100); 
if($_GET['glass'] == 1){ 
imagecopy($canvas, $src2, 0, 0, 0, 0, 16, 16); 

} 
imagealphablending($canvas, true); 
imagesavealpha($canvas, true); 
    header("Content-type: image/png"); 
    imagepng($canvas); 
    imagedestroy($dest); 
imagedestroy($src); 
?> 

Terrain.png爲http://hogofwar.co.uk/experiment/mc/terrain.png(這是透明的)

使用GD時,如何保持透明度?

回答

0

您可以嘗試

Parameters: 

$new_image = image resource identifier such as returned by imagecreatetruecolor(). must be passed by reference 
$image_source = image resource identifier returned by imagecreatefromjpeg, imagecreatefromgif and imagecreatefrompng. must be passed by reference 

<?php 
function setTransparency($new_image,$image_source) 
    { 

      $transparencyIndex = imagecolortransparent($image_source); 
      $transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255); 

      if ($transparencyIndex >= 0) { 
       $transparencyColor = imagecolorsforindex($image_source, $transparencyIndex); 
      } 

      $transparencyIndex = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']); 
      imagefill($new_image, 0, 0, $transparencyIndex); 
      imagecolortransparent($new_image, $transparencyIndex); 

    } 
?> 

您可以查詢詳細情況,

http://www.php.net/manual/en/function.imagecolortransparent.php

+0

不工作目前 因爲我可以解決。 – Hogofwar 2010-09-19 14:59:59

+0

你檢查了鏈接到Yogesh在答案結尾處指定的文檔嗎? – mfolnovich 2010-09-19 17:54:43

0

試試這個:

$img = imagecreatefrompng("yourimage.png"); 
$width = imagesx($img); 
$height = imagesy($img); 
$new_width=500;//this is the new width of the output image 
$newheight=($height/$width)*$new_width; 
$target=imagecreatetruecolor($new_width,$newheight); 
$transparent=imagecolorallocatealpha($target,0,0,0,127); 
imagefill($target,0,0,$transparent); 
imagecopyresampled($target,$img,0,0,0,0,$new_width,$newheight,$width,$height); 
imagealphablending($target,false); 
imagesavealpa($target,true); 
imagepng($target,"your_target_filename.png"); 

完成...