2012-01-10 61 views
0

我有這個圖片,





如何裁切圖像?

我想這個圖像裁剪幾個尺寸,我使用這個功能 -

function thumbanail_for_image($Id, $newfilename, $size=NULL) { 

    $file_extension = substr($newfilename, strrpos($newfilename, '.') + 1); 
    $arr = explode('.', $newfilename); 

    $thumb1 = LOCAL_FOLDER . $arr[0] . "_" . $Id . "." . $file_extension; 
    $thumb2 = LOCAL_FOLDER . $arr[0] . "_" . $Id . "b" . "." . $file_extension; 

    $old = LOCAL_FOLDER . $newfilename; 

    $newfilename = LOCAL_FOLDER . $newfilename; 

    $srcImage = ""; 

    $sizee = getimagesize($newfilename); 

    switch ($sizee['mime']) { 
    case "image/jpeg" : 
     $srcImage = imagecreatefromjpeg($old); 
     break; 
    case "image/png": 
     $srcImage = imagecreatefrompng($old); 
     break; 
    case "image/gif": 
     $srcImage = imagecreatefromgif($old); 
     break; 
    } 
    $srcwidth = $sizee[0]; 
    $srcheight = $sizee[1]; 

    if ($srcwidth > $srcheight || $srcwidth < $srcheight) { 
    $destwidth1 = 65; 
    $rat = $destwidth1/$srcwidth; 
    $destheight1 = (int) ($srcheight * $rat); 
    } 

    elseif ($srcwidth == $srcheight) { 
    $destwidth1 = 65; 
    $destheight1 = 65; 
    } 

    if ($srcwidth > $srcheight || $srcwidth < $srcheight) { 
    $destwidth2 = 300; 
    $rat = $destwidth2/$srcwidth; 
    $destheight2 = (int) ($srcheight * $rat); 
    } 
    elseif ($srcwidth == $srcheight) { 
    $destwidth2 = 300; 
    $destheight2 = 300; 
    } 

    $destImage1 = imagecreatetruecolor($destwidth1, $destheight1); 
    $destImage2 = imagecreatetruecolor($destwidth2, $destheight2); 

    imagecopyresampled($destImage1, $srcImage, 0, 0, 0, 0, $destwidth1, $destheight1, $srcwidth, $srcheight); 
    imagecopyresampled($destImage2, $srcImage, 0, 0, 0, 0, $destwidth2, $destheight2, $srcwidth, $srcheight); 

    if ($sizee['mime'] == "image/jpeg") { 
    imagejpeg($destImage1, $thumb1, 80); 
    imagejpeg($destImage2, $thumb2, 80); 
    } elseif ($sizee['mime'] == "image/png") { 
    imagepng($destImage1, $thumb1, 80); 
    imagepng($destImage2, $thumb2, 80); 
    } elseif ($sizee['mime'] == "image/gif") { 
    imagegif($destImage1, $thumb1, 80); 
    imagegif($destImage2, $thumb2, 80); 
    } 
    imagedestroy($destImage1); 
    imagedestroy($destImage2); 
    chmod($destImage1, 0777); 
    chmod($destImage2, 0777); 
    return $destImage1; 
} 

LOCAL_FOLDER是當地的可變路徑

我看到的問題是,當我打印$ _FILES信息關於它顯示

[type] =>image/jpeg 

,當我打印和getimagesize()函數,它打印

[mime] => image/png 

請幫幫忙, 感謝

回答

1

爲什麼你不使用一個爲你處理所有這些事情的庫?

例如,檢查出WideImage

include "path-to/WideImage.php"; 


$image = WideImage::load("path-to/image.jpg"); 
$cropped = $image->crop(0, 0, 100, 50); 
$cropped->saveToFile("cropped-image.jpg"); 
1

PHP的POST method uploads頁說:

$ _FILES [ 'userfile的'] [ '型']

MIME類型如果瀏覽器提供了這個信息。 一個例子就是「image/gif」。然而,這種MIME類型在PHP方面沒有被檢查 ,因此並不認爲它是理所當然的。

所以這裏的圖片類型數據是由上傳文件的客戶端提供的,PHP建議不要相信它。請相信getimagesize()替代您。