Laravel 5 imagepng 不起作用

Sim*_*duc 3 php laravel laravel-5

我正在尝试创建一个脚本来获取图像的某个部分,但是当我使用 imagepng 时,它返回给我: 在此处输入图片说明

这是我的代码

$name = $path;

header("Content-type: image/png");

if (strpos($name, '..') !== false) {
   exit(); // name in path with '..' in it would allow for directory 
   traversal.
}

$size = $face_size > 0 ? $face_size : 100;

//Grab the skin
$src = imagecreatefrompng("./skins/" . $name . ".png");
//If no path was given or no image can be found, then create from default
if (!$src) {
    $src = imagecreatefrompng("./skins/default.png");
}
//Start creating the image
list($w, $h) = getimagesize("./skins/" . $name . ".png");
$w = $w / 8;

$dest = imagecreatetruecolor($w, $w);
imagecopy($dest, $src, 0, 0, $w, $w, $w, $w);   // copy the face
// Check to see if the helm is not all same color
$bg_color = imagecolorat($src, 0, 0);
$no_helm = true;
// Check if there's any helm
for ($i = 1; $i <= $w; $i++) {
    for ($j = 1; $j <= 4; $j++) {
        // scanning helm area
        if (imagecolorat($src, 40 + $i, 7 + $j) != $bg_color) {
            $no_helm = false;
        }
    }
    if (!$no_helm)
        break;
}
// copy the helm
if (!$no_helm) {
    imagecopy($dest, $src, 0, -1, 40, 7, $w, 4);
}  
//prepare to finish the image
$final = imagecreatetruecolor($size, $size);
imagecopyresized($final, $dest, 0, 0, 0, 0, $size, $size, $w, $w);

//if its not, just show image on screen
imagepng($final);

//Finally some cleanup
imagedestroy($dest);
imagedestroy($final);
Run Code Online (Sandbox Code Playgroud)

我之前在没有任何框架的情况下使用了这段代码,它运行得很好,我不知道它来自哪里。

小智 5

Laravel 和其他框架使用中间件,因此当您的控制器方法完成时,应用程序还没有准备好发送响应。您可以通过将 imagepng 函数的输出存储在内部缓冲区中并正确发送来解决问题(如果您想使用 GD,我认为没有其他解决方案),您还必须使用 Laravel 的函数来设置 HTTP 标头而不是header函数。

这是一个简单的例子:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AppController extends Controller
{
    //Generates an image with GD and sends it to the client.
    public function image(){



    $im = imagecreatetruecolor(800, 420);
    $orange = imagecolorallocate($im, 220, 210, 60);

    imagestring($im, 3, 10, 9, 'Example image', $orange);

    //Turn on output buffering
    ob_start();

    imagepng($im);

    //Store the contents of the output buffer
    $buffer = ob_get_contents();
    // Clean the output buffer and turn off output buffering
    ob_end_clean();

    imagedestroy($im);

    return response($buffer, 200)->header('Content-type', 'image/png');

    }
}
Run Code Online (Sandbox Code Playgroud)

你可以看看这个,希望对你有帮助。

虽然它有效,但它不是最好的方法,我建议您使用 Imagick(如果可以)而不是 GD。