PHP 等比例縮圖及背景透明問題

話說上網試了幾個範例,終於找到一個合用的代碼,但是有兩個問題 google 了兩天,怎麼試都不成功,在此求助:


- 上載後的圖不懂等比例縮小,而是被強行接成 200 x 200
- 上載 png 的話,背景會變成全黑色,而非透明
<?php	
if(is_array($_FILES)) {
	
        $file = $_FILES['userImage']['tmp_name']; 
        $sourceProperties = getimagesize($file);
        $fileNewName = substr(md5(rand(date("Y-m-d"),time())),0,12);
        $folderPath = "upload/";		
        $imageType = $sourceProperties[2];


        switch ($imageType) {


            case IMAGETYPE_PNG:
                $imageResourceId = imagecreatefrompng($file); 
                $targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
                imagepng($targetLayer,$folderPath . $fileNewName . ".png");
                $img_path = $folderPath . $fileNewName . ".png";
                break;


            case IMAGETYPE_GIF:
                $imageResourceId = imagecreatefromgif($file); 
                $targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
                imagegif($targetLayer,$folderPath . $fileNewName . ".gif");
                $img_path = $folderPath . $fileNewName . ".gif";
                break;


            case IMAGETYPE_JPEG:
                $imageResourceId = imagecreatefromjpeg($file); 
                $targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
                imagejpeg($targetLayer,$folderPath . $fileNewName . ".jpg");
                $img_path = $folderPath . $fileNewName . ".jpg";
                break;


            default:
                echo "Error!";
                exit;
                break;
        }	
?>
       <img class="image-preview" src="<?php echo $img_path; ?>" class="upload-preview" width="60px" />
<?
}

function imageResize($imageResourceId,$width,$height) {
    $targetWidth = 200;
    $targetHeight = 200;

    $targetLayer=imagecreatetruecolor($targetWidth,$targetHeight);
    imagecopyresampled($targetLayer,$imageResourceId,0,0,0,0,$targetWidth,$targetHeight, $width,$height);

    return $targetLayer;
}
?>
Sign In or Register to comment.