2013-02-10 49 views
0

我想將上傳的圖像轉換爲其原始格式(jpg,jpeg rpng等),但我需要將這些圖像重新調整爲150像素寬和210像素高。是否可以在複製時更改大小,還是必須將其轉換?已上傳的圖像:轉換格式

這是不成功的:

$uploaddir1 = "/home/myweb/public_html/temp/sfds454.png"; 
    $uploaddir2 = "/home/myweb/public_html/images/sfds454.png"; 

    $cmd = "/usr/bin/ffmpeg -i $uploaddir1 -vframes 1 -s 150x210 -r 1 -f mjpeg $uploaddir2"; 
    @exec($cmd); 

回答

1

我最近不得不解決眼前這個問題,並實現了這個簡單的緩存解決方案:

<?php 
function send($name, $ext) { 
    $fp = fopen($name, 'rb'); 
    // send the right headers 
    header("Content-Type: image/$ext"); 
    header("Content-Length: " . filesize($name)); 

    // dump the picture and stop the script 
    fpassthru($fp); 
    exit; 
} 

error_reporting(E_ALL); 
ini_set('display_errors', 'On'); 

if (isset($_REQUEST['fp'])) { 
    $ext = pathinfo($_REQUEST['fp'], PATHINFO_EXTENSION); 

    $allowedExt = array('png', 'jpg', 'jpeg'); 
    if (!in_array($ext, $allowedExt)) { 
     echo 'fail'; 
    } 

    if (!isset($_REQUEST['w']) && !isset($_REQUEST['h'])) { 
     send($_REQUEST['fp']); 
    } 
    else { 
     $w = $_REQUEST['w']; 
     $h = $_REQUEST['h']; 

     //use height, width, modification time and path to generate a hash 
     //that will become the file name 
     $filePath = realpath($_REQUEST['fp']); 
     $cachePath = md5($filePath.filemtime($filePath).$h.$w); 
     if (!file_exists("tmp/$cachePath")) { 
      exec("gm convert -quality 80% -colorspace RGB -resize " .$w .'x' . $h . " $filePath tmp/$cachePath"); 
     } 
     send("tmp/$cachePath", $ext); 

    } 
} 
?> 

有些事情,我注意到:

  1. GraphicsMagick工具轉換比ImageMagick的快很多,雖然我沒有用cuda處理測試轉換。
  2. 對於最終產品,我使用該語言的原生圖形庫在ASP中重新實現了此代碼。這再次快得多,但如果發生內存不足錯誤會中斷(在我的工作站上正常工作,但在4GB RAM服務器上不起作用)。