2017-07-18 14 views
0

我想用PHP請求的用戶大小顯示圖像。Silex/Symfony Response無法正確返回圖像數據

工作代碼。沒有框架。

<?php 

require_once __DIR__ . '/vendor/autoload.php'; 

define('BASE_SIZE', 1000); 

$original = imagecreatefrompng('image.png'); 

$size = $_REQUEST['size']; 
if($size == BASE_SIZE) { 
    $out = $original; 
} 
else { 
    $out = imagecreatetruecolor($size ,$size); 
    imagecopyresampled($out, $original, 0, 0, 0, 0, $size, $size, BASE_SIZE, BASE_SIZE); 
} 

ob_start(); 
imagepng($out, null, 9); 
$content = ob_get_contents(); 
ob_end_clean(); 

header('Content-type: image/png'); 
echo $content; 

?> 

此編碼顯示正確的圖像。這裏是輸出預覽。

Correct Output

不工作的代碼。使用Silex。

$app->get('/resize/{size}', function (Symfony\Component\HttpFoundation\Request $request, $size) use ($app) { 

    define('BASE_SIZE', 1000); 

    $original = imagecreatefrompng('image.png'); 

    if($size == BASE_SIZE) { 
     $out = $original; 
    } 
    else { 
     $out = imagecreatetruecolor($size ,$size); 
     imagecopyresampled($out, $original, 0, 0, 0, 0, $size, $size, BASE_SIZE, BASE_SIZE); 
    } 

    ob_start(); 
    imagepng($out, null, 9); 
    $content = ob_get_contents(); 
    ob_end_clean(); 

    $response = new Symfony\Component\HttpFoundation\Response($content, 200); 
    $response->headers->set('Content-Type', 'image/png'); 
    $response->headers->set('Content-Disposition', 'inline'); 
    return $response; 
}); 

此代碼顯示損壞的圖像。這裏是輸出預覽。

Incorrect output

而這是標題。

緩存控制:無緩存,私人 連接:保活 內容處置:內聯 內容類型:圖像/ PNG日期:星期二,2017年7月18日6點15分56秒GMT 服務器:阿帕奇 傳輸編碼:分塊 途經:1.1 vegur

我想我接近的答案,但有「<」起初不正確的輸出。我無法正確刪除substr。

我真的有麻煩了。任何想法?

回答

0

檢查你的php文件硅石寫的,有可能在其中之一的開始,導致此問題是一個額外<

+0

就是這樣!非常感謝! – shot

1

size不是GET/POST參數。你應該從$request

$size = $request->get('size'); 

或函數參數

$app->get('/resize/{size}', function (Symfony\Component\HttpFoundation\Request $request, $size) use ($app) { 
    // $size = $_REQUEST['size']; // remove this 

而且Symfony\Component\HttpFoundation\BinaryFileResponse應該爲二進制文件(文件)的反應得到它。

$path = sys_get_temp_dir() . '/qwerty'; 
imagepng($out, $path, 9); 
$response = new \Symfony\Component\HttpFoundation\BinaryFileResponse($path, 200, array('Content-Type'=>'image/png'), false, 'inline'); 
return $response; 
+0

謝謝,我很抱歉,這是我的錯字。代碼如你所說。 '$ size = $ request-> get('size');' – shot