2010-01-29 58 views
6

我正在上傳一張使用PHP的圖片的腳本,我想在保存之前將它調整爲寬度爲180的圖像。
我嘗試使用WideImage庫和 - > saveFileTO(...),但是當我在頁面中包含WideImage.php時,頁面變爲空白!
因此,這裏是我的腳本,如果你能幫助我,告訴我怎麼把它存的調整版本
PHP上傳和調整圖像

回答

6

可以使用PHP GD library對上傳調整圖像大小。

下面的代碼應該給你如何實現調整大小的一個想法:

// Get the image info from the photo 
$image_info = getimagesize($photo); 
$width = $new_width = $image_info[0]; 
$height = $new_height = $image_info[1]; 
$type = $image_info[2]; 

// Load the image 
switch ($type) 
{ 
    case IMAGETYPE_JPEG: 
     $image = imagecreatefromjpeg($photo); 
     break; 
    case IMAGETYPE_GIF: 
     $image = imagecreatefromgif($photo); 
     break; 
    case IMAGETYPE_PNG: 
     $image = imagecreatefrompng($photo); 
     break; 
    default: 
     die('Error loading '.$photo.' - File type '.$type.' not supported'); 
} 

// Create a new, resized image 
$new_width = 180; 
$new_height = $height/($width/$new_width); 
$new_image = imagecreatetruecolor($new_width, $new_height); 
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

// Save the new image over the top of the original photo 
switch ($type) 
{ 
    case IMAGETYPE_JPEG: 
     imagejpeg($new_image, $photo, 100); 
     break; 
    case IMAGETYPE_GIF: 
     imagegif($new_image, $photo);   
     break; 
    case IMAGETYPE_PNG: 
     imagepng($new_image, $photo); 
     break; 
    default: 
     die('Error saving image: '.$photo); 
} 
1

你可以使用我爲這樣一個任務,寫一個類:

http://code.google.com/p/image2/source/browse/#svn/trunk/includes/classes

<?php 

    try 
    { 
     $image = new Image2($path_to_image); 
    } 
    catch (NotAnImageException $e) 
    { 
     printf("FILE PROVIDED IS NOT AN IMAGE, FILE PATH: %s", $path_to_image); 
    } 

    $image -> resize(array("width" => 180)) -> saveToFile($new_path); // be sure to exclude the extension 
    $new_file_location = $image -> getFileLocation(); // this will include the extension for future use 
1

你甚至不需要使用WideImage庫。

檢查這個腳本在這裏: http://bgallz.org/502/php-upload-resize-image/

您可以通過上傳圖片並保存到一個臨時的圖像文件開始。這個腳本運行一個表單,其中包含最大高度或最大寬度的輸入。因此,它會根據新的寬度/高度生成新的圖像文件,然後將臨時圖像複製到服務器上創建的新圖像文件中。

你看這下面的代碼:

// Create temporary image file. 
$tmp = imagecreatetruecolor($newwidth,$newheight); 
// Copy the image to one with the new width and height. 
imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);