Home > Backend Development > PHP Tutorial > 使用 Laravel 开发显示图片

使用 Laravel 开发显示图片

WBOY
Release: 2016-06-06 20:07:00
Original
1714 people have browsed it

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

代码如下:

<code>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',
    ]);
});</code>
Copy after login
Copy after login

出现的问题是:

使用 Laravel 开发显示图片

版本: Laravel Framework version 5.1.35 (LTS)

回复内容:

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

代码如下:

<code>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',
    ]);
});</code>
Copy after login
Copy after login

出现的问题是:

使用 Laravel 开发显示图片

版本: Laravel Framework version 5.1.35 (LTS)

<code>$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');</code>
Copy after login

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

在输出前使用ob_clean(),

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

<code>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',
    ]);
});</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template