2011-08-21 89 views

回答

0

我用這個功能來做到這一點,非常簡單和易於使用的信息。首先把這個功能放到你可以稱之爲的地方。

public function Resize_image($width = 0, $height = 0, $quality = 90, $filename_in = null, $filename_out = null) 
{ 
    $this->Filename = $filename_in; 
    $this->Extension = strtolower($this->Get_file_extension($this->Filename)); 

    $size = getimagesize($this->Filename); 
    $ratio = $size[0]/$size[1]; 
    if ($ratio >= 1){ 
     $scale = $width/$size[0]; 
    } else { 
     $scale = $height/$size[1]; 
    } 
    // make sure its not smaller to begin with! 
    if ($width >= $size[0] && $height >= $size[1]){ 
     $scale = 1; 
    } 

    // echo $fileext; 
    switch ($this->Extension) 
    { 
     case "jpg": 
      $im_in = imagecreatefromjpeg($this->Filename); 
      $im_out = imagecreatetruecolor($size[0] * $scale, $size[1] * $scale); 
      imagecopyresampled($im_out, $im_in, 0, 0, 0, 0, $size[0] * $scale, $size[1] * $scale, $size[0], $size[1]); 
      imagejpeg($im_out, $filename_out, $quality); 
     break; 
     case "gif": 
      $im_in = imagecreatefromgif($this->Filename); 
      $im_out = imagecreatetruecolor($size[0] * $scale, $size[1] * $scale); 
      imagecopyresampled($im_out, $im_in, 0, 0, 0, 0, $size[0] * $scale, $size[1] * $scale, $size[0], $size[1]); 
      imagegif($im_out, $filename_out, $quality); 
     break; 
     case "png": 
      $im_in = imagecreatefrompng($this->Filename); 
      $im_out = imagecreatetruecolor($size[0] * $scale, $size[1] * $scale); 
      imagealphablending($im_in, true); // setting alpha blending on 
      imagesavealpha($im_in, true); // save alphablending setting (important) 
      imagecopyresampled($im_out, $im_in, 0, 0, 0, 0, $size[0] * $scale, $size[1] * $scale, $size[0], $size[1]); 
      imagepng($im_out, $filename_out, 9); 
     break; 
    } 
    imagedestroy($im_out); 
    imagedestroy($im_in); 
} 

現在你可以使用這個功能,像這樣來調整圖像並將其複製到所需的目錄。

Resize_image($width, $height, $quality=90, $filename_in, $filename_out) 
Example.. 
Resize_image(150, 150, 90, "Directory".$image, "Directory".$image_without_extension."_thumb.".$image_ext); //makes file_thumb.ext 
+0

謝謝,結束了使用的這種變體。 – RonnieT

2

你可能想看看PHP文檔:Handling file uploadsGD and Image Functions

一般情況下,你必須:

  1. 上傳文件(並檢查它是否是真正的用is_uploaded_file上傳的文件)
  2. 檢測圖像類型與getimagesize然後用適當的imagecreatefrom*函數來創建圖像資源($img

    $thumb = imagecreatetruecolor($width, $height); 
    imagecopyresampled($thumb, $img, 0, 0, 0, 0, $width, $height, imagexs($img), imagesy($img)); 
    
  3. :像這樣的東西)
  4. 調整圖像大小

  5. 保存縮略圖:

    imagejpeg($thumb, 'file.jpg', 85); 
    imagedestroy($thumb); // free memory 
    imagedestroy($img); // free memory 
    
  6. 保存,你需要你的MySQL數據庫