return dynamic image zf2

血红的双手。 提交于 2019-12-13 06:20:21

问题


I use zend framework 2 and try to return an created with gd2 library jpeg image . but it doesn't work. could you look my code what's the problem? My code is run with plain php in normally but in zf2 problem?

class PictureController extends AbstractActionController
{
    public function colorPaletteAction(){

        ....
        ....
        //canvas created at above.

        imagejpeg($canvas);
        imagedestroy($canvas);
        $response = $this->getResponse();

        return $response->getHeaders()->addHeaderLine('Content-Type', 'image/jpeg');
    }
}

回答1:


imagejpeg outputs the data immediately which you don't want to do. You can either use the output buffer to capture this data or write it to a file first. The output buffer is probably easiest:

public function colorPaletteAction()
{
    // [create $canvas]

    ob_start();
    imagejpeg($canvas);
    $imageData = ob_get_contents();
    ob_end_clean();

    imagedestroy($canvas);

    $response = $this->getResponse();

    $response->getHeaders()->addHeaderLine('Content-Type', 'image/jpeg');
    $response->setContent($imageData);

    return $response;
}

If this doesn't work, temporarily comment out the Content-Type header line to see what output you're getting. Make sure there aren't any errors or HTML in the output.




回答2:


You set the Content-Type header to 'image/png' instead of 'image/jpeg'.

Also try adding the content-transfer-encoding and content-length headers:

$response->getHeaders()->addHeaderLine('Content-Transfer-Encoding', 'binary')
                       ->addHeaderLine('Content-Length', mb_strlen($yourJpegContent));

I also don't see you adding the actual content to the response:

$response->setContent($yourJpegContent);

where $yourJpegContent contains the binary image data.



来源:https://stackoverflow.com/questions/24437458/return-dynamic-image-zf2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!