简体   繁体   中英

PHP - Save Dynamically Created Image on Server

I am attempting to create a dynamic image using the Google QR Code Generator via PHP and then want to save that image to a temp directory on the server. I am thinking I am close, however I don't code in PHP that often, so I need some additional guidance.

Here's the code I have:

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

Thanks for any and all insight.

Unless you are actually making changes to the image (resizing, drawing, etc), you don't need to use GD to create a new image. You can just use file_get_contents to get the image and file_put_contents to save it somewhere. And for showing the image, just echo what you got back from file_get_contents after sending out the header.

Example:

<?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;
}

I guess you've too much code, use something like:

<?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

Note that you don't need tho use the GD library since the image is already generated by googleapis, this will be enough:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM