PHP - 在服务器上保存动态创建的图像
问题描述:
我试图通过PHP使用Google QR代码生成器创建动态图像,然后想要将该图像保存到服务器上的临时目录中。我想我很接近,但是我经常不用PHP编写代码,所以我需要一些额外的指导。PHP - 在服务器上保存动态创建的图像
这里是我的代码:
header("content-type: image/png");
$url = "https://chart.googleapis.com/chart?chs=177x177&cht=qr&chl=MyHiddenCode&choe=UTF-8";
$qr_image = imagecreatefrompng(file_get_contents($url));
$cwd = getcwd();
$cwd = $cwd . "/temp";
$save = "$cwd"."/chart123.png";
imagepng($qr_image);
chmod($save,0755);
imagepng($qr_image,$save,0,NULL);
感谢您的任何和所有的洞察力。
答
除非实际上对图像进行更改(调整大小,绘制等),否则不需要使用GD创建新图像。您只需使用file_get_contents
即可获取图像,而file_put_contents
可将其保存在某处。为了显示图像,只需在发送标题后回显你从file_get_contents
得到的回复。
例子:
<?php
//debug, leave this in while testing
error_reporting(E_ALL);
ini_set('display_errors', 1);
$url = "url for google here";
$imageName = "chart123.png";
$savePath = getcwd() . "/temp/" . $imageName;
//try to get the image
$image = file_get_contents($url);
//try to save the image
file_put_contents($savePath, $image);
//output the image
//if the headers haven't been sent yet, meaning no output like errors
if(!headers_sent()){
//send the png header
header("Content-Type: image/png", true, 200);
//output the image
echo $image;
}
+0
谢谢!!!!!! – azsl1326
答
我想你已经太多的代码,使用类似:
<?php
header("content-type: image/png");
$qr_image = imagecreatefrompng("https://chart.googleapis.com/chart?chs=177x177&cht=qr&chl=MyHiddenCode&choe=UTF-8"); //no need for file_get_contents
$save = getcwd()."/temp/chart123.png";
imagepng($qr_image,$save); //save the file to $save path
imagepng($qr_image); //display the image
请注意,您不需要使用寿GD库自图像已经由googleapis生成,这就足够了:
header("content-type: image/png");
$img = file_get_contents("https://chart.googleapis.com/chart?chs=177x177&cht=qr&chl=MyHiddenCode&choe=UTF-8");
file_put_contents(getcwd()."/temp/chart123.png", $img);
echo $img;
你有什么错误? –
https://github.com/Pamblam/EasyImage - >'EasyImage :: Create($ url) - > save($ save);'你的代码看起来不错,可能需要调整目录中的权限保存为' –
当你运行'chmod()'时文件是否存在? – WillardSolutions