PHP-在服务器上保存动态创建的图像


PHP - Save Dynamically Created Image on Server

我正试图通过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;
}

我想您的代码太多了,请使用以下内容:

<?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库,因为图像已经由googleapi生成,这就足够了:

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;