2014-09-01 89 views
0

我有這段代碼用於圖像上傳,現在我需要調整上傳的圖像大小以減小文件大小和寬度/高度。我發現圖像調整大小的代碼(註釋),但我不明白它足以正確實現它。什麼應該糾正?調整大小並覆蓋上傳的圖像

$path = ($_FILES['image']['name']); 
$ext = pathinfo($path, PATHINFO_EXTENSION); 

$ran = time(); 
$ran2 = $ran."."; 
$target = "img/$userid/"; 
$target = $target . $ran2.$ext; 

if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){ 

//I tried this resize code below but it doesn't work 

    $file = "$target"; 
    $type = exif_imagetype($file); 
    switch ($type) 
    { 
     case IMAGETYPE_GIF: 
      $img = imagecreatefromgif($file); 
      break; 
     case IMAGETYPE_JPEG: 
      $img = imagecreatefromjpeg($file); 
      break; 
     case IMAGETYPE_PNG: 
      $img = imagecreatefrompng($file); 
      break; 
     default: 
      throw new Exception('Unrecognized image type ' . $type); 
    } 

    $width = imagesx($img); 
    $height = imagesy($img); 
    $max_width = 600; 
    $max_height = 600; 
    $percentage = 1; 

    if ($width > $max_width) { 
     $percentage = ($height/($width/$max_width)) > $max_height ? 
      $height/$max_height : 
      $width/$max_width; 
    } 
    elseif ($height > $max_height) { 
     $percentage = ($width/($height/$max_height)) > $max_width ? 
      $width/$max_width : 
      $height/$max_height; 
    } 
    $new_width = $width/$percentage; 
    $new_height = $height/$percentage; 

    $out = imagecreatetruecolor($new_width, $new_height); 
    imagecopyresampled($out, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

    imagejpeg($out); 

// Image resize code end 

$query="UPDATE user SET image='$ran2$ext' WHERE id='$userid'"; 
$result = mysqli_query($db, $query) or die (mysqli_error($db)); 
} 
else 
{ 
echo "Sorry, there was a problem uploading your file."; 
} 
+0

什麼具體不工作?你有錯誤嗎?意外的結果?它在哪裏失敗? – David 2014-09-01 20:25:53

+0

嘗試使用$文件= $目標,而不是$文件=「$目標」 – Zack 2014-09-01 20:28:06

+0

@大衛圖像上傳,但與原始大小和一堆代碼顯示在頁面上。這只是一部分:'˙Ř˙ŕJFIF˙ţ> CREATOR:gd-jpeg v1.0(使用IJG JPEG v62),默認品質˙ŰC\t $。' 「,#(7),01444'' – jakob 2014-09-01 20:31:22

回答

0

問題是這一行

imagejpeg($out); 

你需要指定你想要它去,否則會打印出來給瀏覽器。

imagejpeg($out,$filepath); 

這會將圖像放在文件路徑所在的位置。請記住,文件路徑必須以.jpg結尾,否則文件將不會是jpeg文件。

+0

ty,我發現它:)我這一刻自己正在寫解決方案。 – jakob 2014-09-01 20:53:40