2011-10-12 172 views
1

我有一段简单的代码,将来自谷歌发布请求的数据流作为PNG输出。这是为了使用谷歌创建一个QRcode。我想要做的是将此文件保存为我的服务器上的PNG文件,我似乎无法弄清楚如何处理它,因为我不熟悉使用流。下面的代码:通过Google POST请求保存PNG

<?php 

    //This script will generate the slug ID and create a QRCode by requesting it from Google Chart API 
    header('content-type: image/png'); 

    $url = 'https://chart.googleapis.com/chart?'; 
    $chs = 'chs=150x150'; 
    $cht = 'cht=qr'; 
    $chl = 'chl='.urlencode('Hello World!'); 

    $qstring = $url ."&". $chs ."&". $cht ."&". $chl;  

    // Send the request, and print out the returned bytes. 
    $context = stream_context_create(
     array('http' => array(
      'method' => 'POST', 
      'content' => $qstring 
    ))); 
    fpassthru(fopen($url, 'r', false, $context)); 

?> 
+0

是否必须是帖子?生成的url作为一个简单的GET请求正常工作,这意味着您可以使用'echo file_get_contents(...)'代替。 –

+0

它可以是一个获取请求,但仍然不确定我将如何保存它。 http://code.google.com/apis/chart/infographics/docs/overview.html – Throttlehead

+0

'file_put_contents('qr.png',file_get_contents(...));'fpassthru()用于直接发送输出到客户。对于你的代码,你需要在之前打开的文件句柄上使用fwrite()。 –

回答

2

这是一种方式,根据您的代码,并指定“这个保存为我的服务器上的PNG文件”:

<?php 
$url = 'https://chart.googleapis.com/chart?'; 
$chs = 'chs=150x150'; 
$cht = 'cht=qr'; 
$chl = 'chl='.urlencode('Hello World!'); 

$qstring = $url ."&". $chs ."&". $cht ."&". $chl;  

$data = file_get_contents($qstring); 

$f = fopen('file.png', 'w'); 
fwrite($f, $data); 
fclose($f); 

添加错误检查等调味。

+0

请让我知道如何创建带标识的二维码 –

+0

嗨达人,它的工作很好。但是,如何添加此条形码图片的徽标中心?任何想法请分享 –

1

要将结果写入文件,请使用fwrite()而不是fpassthru()。

您可以使用file_get_contents()和file_put_contents(),但是这些需要将整个图像存储在一个字符串中,这对于大图像可能需要大量内存。这里没有问题,因为qrcode图像很小,但一般来说值得考虑。

您并不需要创建流上下文,因为Web服务可以正常使用HTTP GET而不是POST。

还有一个名为http_build_query()的函数,您可以使用它来简化构建URL。

<?php 

$url = 'https://chart.googleapis.com/chart?' . http_build_query(array(
    'chs' => '150x150', 
    'cht' => 'qr', 
    'chl' => 'Hello World!' 
)); 

$src = fopen($url, 'rb'); 
$dst = fopen('file.png', 'w'); 
while (!feof($src)) { 
    fwrite($dst, fread($src, 1024)); 
} 

?>