2012-02-17 102 views
0

我没有保存图像后,我只想按百分比来缩小图像,然后在网页上显示它PHP临时缩略图

我知道我可以使用和getimagesize得到高度宽度,但如何正确缩放?

+1

imagecopyresampled:HTTP:/ /php.net/manual/en/function.imagecopyresampled.php – dbrumann 2012-02-17 10:33:52

+1

查看PHP GD库。 – deed02392 2012-02-17 10:33:59

+0

@mahok完美谢谢你! – user1083382 2012-02-17 11:02:00

回答

1

您可以使用这样的功能。

参考http://tutorialfeed.net/development/scale-an-image-using-php

function create_thumb($imgSrc, $thumbnail_width, $thumbnail_height, $dest_src, $ext) 
    { 
     //getting the image dimensions 
     list($width_orig, $height_orig) = getimagesize($imgSrc); 

     // Check if the images is a gif 
     if($ext == 'gif') 
     { 
      $myImage = imagecreatefromgif($imgSrc); 
     } 
     // Check if the image is a png 
     elseif($ext == 'png') 
     { 
      $myImage = imagecreatefrompng($imgSrc); 
     } 
     // Otherwise, file is jpeg 
     else 
     { 
      $myImage = imagecreatefromjpeg($imgSrc); 
     } 

     // Find the original ratio 
     $ratio_orig = $width_orig/$height_orig; 

     // Check whether to scale initially by height or by width 
     if($thumbnail_width/$thumbnail_height > $ratio_orig) 
     { 
      $new_height = $thumbnail_width/$ratio_orig; 
      $new_width = $thumbnail_width; 
     } 
     else 
     { 
      $new_width  = $thumbnail_height*$ratio_orig; 
      $new_height = $thumbnail_height; 
     } 

     $x_mid = $new_width/2; //horizontal middle 
     $y_mid = $new_height/2; //vertical middle 

     $process = imagecreatetruecolor(round($new_width), round($new_height)); 

     // Scale the image down and the reduce the other axis to create the thumbnail 
     imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig); 
     $thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height); 
     imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height); 

     // Depending on the file extension, save the file 
     if($ext == 'gif') 
     { 
      imagegif($thumb, $dest_src); 
     } 
     elseif($ext == 'png') 
     { 
      imagepng($thumb, $dest_src); 
     } 
     else 
     { 
      imagejpeg($thumb, $dest_src, 100); 
     } 

     // Remove rubbish file data 
     imagedestroy($process); 
     imagedestroy($myImage); 

     // Return thumb (success/fail) 
     return $thumb; 
    } 
+0

我最终使用了它,因为它适用于所有文件类型,谢谢 – user1083382 2012-02-17 11:27:05