【问题标题】:Symfony2 send image created with imagecreate() via response(httpfoundation)Symfony2 通过响应(httpfoundation)发送使用 imagecreate() 创建的图像
【发布时间】:2014-12-22 23:50:41
【问题描述】:

我想通过 httpgoundation 响应发送简单的图像,从一个控制器到另一个控制器。这是我的代码:

    $string = (string)md5(uniqid());
    $string = substr($string, 0, $length);

    $image = imagecreate(200, 50);
    imagefill($image, 0, 0, "#000000");

    $headers= array(
        'Content-type'=>'image/jpeg',
        'Pragma'=>'no-cache',
        'Cache-Control'=>'no-cache'
    );

    $response = new Response( $image, 200, $headers );

    return new Response($response);

错误为The Response content must be a string or object implementing __toString()。使用谷歌寻求答案我只发现想要从服务器(资产)某处返回文件的人。我应该怎么做才能让它工作?

【问题讨论】:

    标签: php symfony captcha


    【解决方案1】:

    您必须使用return $response; 而不是return new Response($response);

    而且您必须将图像资源转换为字符串。执行以下操作:

        $string = (string)md5(uniqid());
        $string = substr($string, 0, $length);
    
        $image = imagecreate(200, 50);
        imagefill($image, 0, 0, "#000000");
    
        $headers= array(
            'Content-type'=>'image/jpeg',
            'Pragma'=>'no-cache',
            'Cache-Control'=>'no-cache'
        );
    
        ob_start();
        imagejpeg($img);
        $imageString = ob_get_clean();
    
        return new Response( $imageString, 200, $headers );
    

    【讨论】:

    • 似乎可以正常工作,谢谢!但是现在在另一个控制器中,您知道如何将其转换为图像,因为我有一个大而奇怪的字符串。我使用了imagecreatefromstring(),但它只返回类似:Resource id #11
    猜你喜欢
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 2015-09-27
    • 2012-08-27
    • 2014-01-16
    相关资源
    最近更新 更多