gpt4 book ai didi

php - Laravel 5 imagepng 不工作

转载 作者:行者123 更新时间:2023-12-04 02:59:10 27 4
gpt4 key购买 nike

我正在尝试创建一个脚本来获取图像的特定部分,但是当我使用 imagepng 时,它返回给我: enter image description here

这是我的代码

$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);

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

最佳答案

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

}
}

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

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

关于php - Laravel 5 imagepng 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50893076/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com