2012-07-06 128 views
4

你能幫我用我的代碼在PHP?Png黑色背景上傳和調整圖像大小

我不知道如何讓我的照片透明。上傳後他們有黑色背景。我在這裏有代碼。 (和一些小文章和內容的文字)

非常感謝。

<?php 
function zmensi_obrazok($image_max_width, $image_max_height, $obrazok, $obrazok_tmp, $obrazok_size, $filename){ 

$postvars   = array(
"image"   => $obrazok, 
"image_tmp"  => $obrazok_tmp, 
"image_size"  => $obrazok_size, 
"image_max_width" => $image_max_width, 
"image_max_height" => $image_max_height 
); 

$valid_exts = array("jpg","jpeg","png"); 
$ext = end(explode(".",strtolower($obrazok))); 
if($postvars["image_size"] <= 1024000){ 


if(in_array($ext,$valid_exts)){ 




if($ext == "jpg" || $ext == "jpeg"){ 
$image = imagecreatefromjpeg($postvars["image_tmp"]); 
} 
else if($ext == "png"){ 
$image = imagecreatefrompng($postvars["image_tmp"]); 
} 


list($width,$height) = getimagesize($postvars["image_tmp"]); 


$old_width  = imagesx($image); 
$old_height  = imagesy($image); 
$scale   = min($postvars["image_max_width"]/$old_width, $postvars["image_max_height"]/$old_height); 
$new_width  = ceil($scale*$old_width); 
$new_height  = ceil($scale*$old_height); 


$tmp = imagecreatetruecolor($new_width,$new_height); 

imagecopyresampled($tmp,$image,0,0,0,0,$new_width,$new_height,$width,$height); 


imagejpeg($tmp,$filename,100); 
return ""; 
imagedestroy($image); 
imagedestroy($tmp); 


} 

} 

} 

?> 
+0

研究imagepng()和imagesavealpaha()... – Brant 2012-07-06 14:35:24

回答

4

我覺得這個鏈接將回答你的問題: http://www.php.net/manual/pl/function.imagecopyresampled.php#104028

在代碼中的答案是這樣的:

// preserve transparency 
    if($ext == "gif" or $ext == "png"){ 
    imagecolortransparent($tmp, imagecolorallocatealpha($tmp, 0, 0, 0, 127)); 
    imagealphablending($tmp, false); 
    imagesavealpha($tmp, true); 
    } 

執行imagecopyresampled前粘貼此。

+0

我試過這個,但它沒有工作。 :(我嘗試了所有的東西,你能幫助我,並改變代碼嗎?我真的不知道如何解決它。 -/ – user1468448 2012-07-06 14:41:22

+0

你幫助變形pictore,並使線更難 – user1468448 2012-07-06 14:42:31

+0

YEAH!它的工作,我改變了imagejpeg爲imagepng($ tmp,$ filename,9);謝謝:) – user1468448 2012-07-06 14:43:46

1

如果你確實想保存爲JPEG而不是保存爲PNG,你可以改變目標圖像白色的背景顏色,你做副本之前:

$tmp = imagecreatetruecolor($new_width,$new_height); 
imagefilledrectangle($tmp, 0, 0, $new_width, $new_height, imagecolorallocate($tmp, 255, 255, 255)); 
imagecopyresampled($tmp,$image,0,0,0,0,$new_width,$new_height,$width,$height); 

,那麼你就最終得到的JPEG沒有任何透明度,但背景顏色將是白色而不是黑色。