首页 > 使用 Laravel 开发显示图片

使用 Laravel 开发显示图片

首先将php原生代码写在PHP 中, 结果出现

代码如下:

Route::get('png', function () {
    ob_start();
    $im = @imagecreate(200, 50) or die("创建图像资源失败");
    imagecolorallocate($im, 255, 255, 255);
    $text_color = imagecolorallocate($im, 0, 0, 255);
    imagestring($im, 5, 0, 0, "Hello world!", $text_color);
    imagepng($im);
    imagedestroy($im);
    $content = ob_get_clean();
    return response($content, 200, [
        'Content-Type' => 'image/png',
    ]);
});

出现的问题是:

版本: Laravel Framework version 5.1.35 (LTS)


这是经过以上几个程序员调整之后的结果. 谢谢大家

Route::get('png', function () {
    ob_clean();
    ob_start();
    $im = @imagecreate(200, 50) or die("创建图像资源失败");
    imagecolorallocate($im, 255, 255, 255);
    $text_color = imagecolorallocate($im, 0, 0, 255);
    imagestring($im, 5, 0, 0, "Hello world!", $text_color);
    imagepng($im);
    imagedestroy($im);
    $content = ob_get_clean();
    return response($content, 200, [
        'Content-Type' => 'image/png',
    ]);
});

在输出前使用ob_clean(),


$im = @imagecreate(200, 50) or die("创建图像资源失败");
imagecolorallocate($im, 255, 255, 255);
$text_color = imagecolorallocate($im, 0, 0, 255);
imagestring($im, 5, 0, 0, "Hello world!", $text_color);
ob_start();
imagepng($im);
$content = ob_get_contents();
imagedestroy($im);
ob_end_clean();
return $response = Response::make($content)->header('Content-Type', 'image/png');

应该是为了规范性 Laravel 对响应头进行了处理,所以你在 console 中会发现你的 Header 头信息被覆盖了,最好都有个 return

【热门文章】
【热门文章】