2017-02-23 70 views
1

嗨我使用php的gd库来生成图像。我已经决定将它融入到laravel中,并且我设法让它工作。Laravel生成图像并添加内容类型标题

我的问题是,如果laravel有时会覆盖我的内容类型标题。

这是我的控制器:

public function imga($algorythm,$w=false,$h=false){ 
    if (!$w) $w=rand(250,750); 
    if (!$h) $h=rand(250,750); 
    $im = imagecreatetruecolor($w, $h); 

    //Here some fancy function is called 
    if (method_exists($this,'img_'.$algorythm)){ 
     $this->{'img_'.$algorythm}($im,$w,$h); 
    } 

    header("Content-type: image/png"); 
    imagepng($im); 
    imagedestroy($im); 
} 

大部分的时间,如果图像是足够大的浏览器只显示它不如预期,但如果图片太小laravel覆盖内容类型标题以“文本/ html; charset = UTF-8“。

我读过https://laravel.com/docs/5.4/responses,但为了让它这样我需要一个字符串。

所以我看过这个:PHP: create image with ImagePng and convert with base64_encode in a single file?但我不确定这是否正确的方式,它看起来像一个肮脏的黑客给我。

我应该把imagepng调用放入一个视图并在那里添加标题,这不是有点矫枉过正吗?

如何使用输出数据而不是在laravel中返回的函数。

回答

2

Laravel控制器的操作通常会给出某种响应,默认为text/html

你修复可能是那么容易,因为:

header("Content-Type: image/png"); 
    imagepng($im); 
    imagedestroy($im); 
    exit; 
} 

或者您可以使用一个包状的干预(http://image.intervention.io)。从中可以生成图像响应。

+0

你的意思是我只需要在末尾添加退出? – Falk

+0

是的,它会停止执行,所以没有更多的标题或其他内容将被添加到输出,图像将显示原样。 – Robert

+0

太棒了! – Falk

1

一种方法是捕捉图像输出与​​然后进行与响应:

public function imga($algorythm,$w=false,$h=false){ 
    if (!$w) $w=rand(250,750); 
    if (!$h) $h=rand(250,750); 
    $im = imagecreatetruecolor($w, $h); 

    //Here some fancy function is called 
    if (method_exists($this,'img_'.$algorythm)){ 
     $this->{'img_'.$algorythm}($im,$w,$h); 
    } 


    ob_start(); 
    $rendered_buffer = imagepng($im); 
    $buffer = ob_get_contents(); 
    imagedestroy($im); 
    ob_end_clean(); 

    $response = Response::make($rendered_buffer); 
    $response->header('Content-Type', 'image/png'); 
    return $response; 
} 

编辑:刚刚看到你的链接,这基本上只是一个实现。

如果你想要一个“更laravel”的方式,你可以保存图像,返回它,然后将其删除:

public function imga($algorythm,$w=false,$h=false){ 
    if (!$w) $w=rand(250,750); 
    if (!$h) $h=rand(250,750); 
    $im = imagecreatetruecolor($w, $h); 

    //Here some fancy function is called 
    if (method_exists($this,'img_'.$algorythm)){ 
     $this->{'img_'.$algorythm}($im,$w,$h); 
    } 

    // store the image 
    $filepath = storage_path('tmpimg/' . uniqid() . '.png'); 
    imagepng($im, $filepath); 
    imagedestroy($im); 

    $headers = array(
     'Content-Type' => 'image/png' 
    ); 

    // respond with the image then delete it 
    return response()->file($filepath, $headers)->deleteFileAfterSend(true); 
} 
+0

太棒了,工作正常! – Falk