2015-09-28 100 views
0

我有這段代碼上傳圖片。它使用PNG 9級壓縮擴展縮略圖,但圖像看起來不太好。我只需要-50%或更多的壓縮PNG與透明度。壓縮的PNG

$path_thumbs = "../pictures/thumbs/"; 
$path_big = "../pictures/"; 
$img_thumb_width = 140; // 
$extlimit = "yes"; 
$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");  
$file_type = $_FILES['image']['type']; 
$file_name = $_FILES['image']['name']; 
$file_size = $_FILES['image']['size']; 
$file_tmp = $_FILES['image']['tmp_name']; 

if(!is_uploaded_file($file_tmp)){ 
    echo "choose file for upload!. <br>--<a href=\"$_SERVER[PHP_SELF]\">return</a>"; 
    exit(); 
} 

$ext = strrchr($file_name,'.'); 
$ext = strtolower($ext); 
if (($extlimit == "yes") && (!in_array($ext,$limitedext))) { 
    echo "dissallowed! <br>--<a href=\"$_SERVER[PHP_SELF]\">return</a>"; 
    exit(); 
} 

$getExt = explode ('.', $file_name); 
$file_ext = $getExt[count($getExt)-1]; 
$rand_name = md5(time()); 
$rand_name= rand(0,10000); 
$ThumbWidth = $img_thumb_width; 

if($file_size){ 
    if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){ 
     $new_img = imagecreatefromjpeg($file_tmp); 
    }elseif($file_type == "image/x-png" || $file_type == "image/png"){ 
     $new_img = imagecreatefrompng($file_tmp); 
    }elseif($file_type == "image/gif"){ 
     $new_img = imagecreatefromgif($file_tmp); 
    } 

    list($width, $height) = getimagesize($file_tmp); 
    $imgratio = $width/$height; 

    if ($imgratio>1){ 
     $newwidth = $ThumbWidth; 
     $newheight = $ThumbWidth/$imgratio; 
    }else{ 
     $newheight = $ThumbWidth; 
     $newwidth = $ThumbWidth*$imgratio; 
    } 
    if (@function_exists(imagecreatetruecolor)){ 
     $resized_img = imagecreatetruecolor($newwidth, $newheight); 
    }else{ 
     die("Error: Please make sure you have GD library ver 2+"); 
    } 
    imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
    ImagePng ($resized_img, "$path_thumbs/$rand_name.$file_ext,9"); 
    ImageDestroy ($resized_img); 
    ImageDestroy ($new_img); 
} 

move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext"); 

回答

0

我覺得(我沒有驗證),你應該使用功能imagecopyresampled代替imagecopyresize的。我認爲imagecopyresampled具有更高的質量。您可能還想使用imagecreatetruecolor

1

爲了更好地改善圖像大小,請使用imagecopyresampledimagecopyresized

對於圖像透明度,你應該看看imagesavealpha
要使其工作,您需要啓用它,然後再調整圖像大小,並且還需要禁用Alpha混合。最好把它放在imagecreatetruecolor之後。

$resized_img = imagecreatetruecolor($newwidth, $newheight); 
imagealphablending($resized_img, false); 
imagesavealpha($resized_img, true); 

至於大小,你有你的代碼

ImagePng ($resized_img,"$path_thumbs/$rand_name.$file_ext,9"); 

一個錯字應

ImagePng ($resized_img, "$path_thumbs/$rand_name.$file_ext", 9); 

你把你的壓縮級別參數爲文件名,而不是功能。

這裏的壓縮級別並不意味着它會使您的文件大小更小。這是速度和文件大小之間的折衷。
你可以無損壓縮一個文件有多少限制。 如果文件大小是一個問題,你應該使用像JPEG這樣的有損壓縮來壓縮它。

+0

我打算使用PNG.Can你能幫助在哪裏添加Imagesavealpha? –