2011-05-17 41 views
-1

我使用下面的函數來重新調整圖片大小。但是我今天試了一下,它不停地給我說,圖片的名稱和路徑是不是一個有效的資源雖然名稱和路徑是相當correct.This錯誤消息的功能:使用php調整圖片大小的問題

function createthumb($name, $filename, $new_w, $new_h) { 
    $system = explode(".", $name); 
    if (preg_match("/jpeg|jpg|JPG/", $system[1])) { 
     $src_img = imagecreatefromjpeg($name); 
    } 
    if (preg_match("/png/", $system[1])) { 
     $src_img = imagecreatefrompng($name); 
    } 
    $old_x = imageSX($src_img); 
    $old_y = imageSY($src_img); 
    if ($old_x > $old_y) { 
     $thumb_w = $new_w; 
     $thumb_h = $old_y * ($new_h/$old_x); 
    } 
    if ($old_x < $old_y) { 
     $thumb_w = $old_x * ($new_w/$old_y); 
     $thumb_h = $new_h; 
    } 
    if ($old_x == $old_y) { 
     $thumb_w = $new_w; 
     $thumb_h = $new_h; 
    } 
    $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h); 
    imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y); 
    if (preg_match("/png/", $system[1])) { 
     imagepng($dst_img, $filename); 
    } else { 
     imagejpeg($dst_img, $filename); 
    } 
    imagedestroy($dst_img); 
    imagedestroy($src_img); 
} 

我這樣使用它

$path = "photos/".$row->pic_name; 
createthumb($path, $path, 350, 180); 

我希望它調整大小的圖片和覆蓋原來的(源)。

$row->pic_name來自數據庫,問題不在於此。 我一直在使用這種方式,它的工作原理,但不是這次,也許我應該嘗試一個更好的?

感謝您的任何建議。

+0

你會得到什麼錯誤信息,並在哪一行? – 2011-05-17 18:48:40

+0

如果文件名包含一個點,那麼你的腳本有bug,請考慮'foo.bar.jpg'。你可以轉儲實際的文件名? – alexn 2011-05-17 18:49:27

+0

檢查imagecreatefrom ...()調用後'$ src_img'是否爲false。另外,如果某人在名爲'haha.pngpong'的文件中上傳了一些隨機垃圾,會發生什麼?檢查文件擴展名並不是檢查你是否有圖像的好方法。 – 2011-05-17 18:52:32

回答

0

我知道一個簡單的方法。這是ImageMagic

轉換調整

1

我會強烈建議您使用getimagesize()功能,從中你可以得到$old_x(或者更準確$old_w)和$old_y$old_h?),最重要IMAGETYPE_XXX不變這表示圖像類型。這將排除的問題,2個可能的原因在你的代碼:

  1. 如果文件類型是大寫的不同,如果文件名中含有較多的點腳本的檢測將通過alexn提到的故障(例如PNGJpG
  2. 將採用錯誤的部分名稱。

如果您更願意堅持自己的方式,你至少可以做

$type = strtolower(array_pop($system)); 
if ($type == 'jpg' || $type == 'jpeg') {  
    $src_img = imagecreatefromjpeg($name); 
} elseif ($type == 'png') { 
    $src_img = imagecreatefrompng($name); 
} 

使用正則表達式像/png/這裏矯枉過正 - strpos(...) !== false會做相同的,但速度要快得多。您不需要正則表達式來進行簡單的子字符串搜索。

最後,不會用它的大拇指覆蓋圖像導致您有任何問題?