-1

我想在 PHP 中创建一个小函数,它接收一个卷曲的值并将其作为图像输出。我通读了 PHP 图像处理和 GD,但我似乎在某处有一个逻辑错误,因为我得到的只是一张空白图像,尽管我得到的值没有问题。有人看到我哪里出错了吗?

<?php
// Dynamic value on an image 
header("Content-type: image/png");

// Get value from API.
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json',
'Content-Type:  application/json'));
curl_setopt($c, CURLOPT_URL, 'https://www.bitstamp.net/api/ticker/');

$data = curl_exec($c);
curl_close($c);

$obj = json_decode($data);

$price = round((40/($obj->{'last'})),3);
$image = imagecreatefrompng("price.png");
$color = ImageColorAllocate($image, 0, 0, 255);

// Calculate horizontal alignment for the value.
$BoundingBox1 = imagettfbbox(13, 0, 'ITCKRIST.TTF', $price);
$boyX = ceil((125 - $BoundingBox1[2]) / 2);

// Write value.
imagettftext($image, 13, 0, $boyX+25, 92, $color, 'ITCKRIST.TTF', $price);

// Return output.
ImageJPEG($image, NULL, 93);
ImageDestroy($image);
?>
4

1 回答 1

0

您的内容类型和数据不匹配。

您暗示您的图像文件是 PNG

header("Content-type: image/png");

但是你输出一个JPEG

ImageJPEG($image, NULL, 93);

还有关于你的字体文件

根据 PHP 使用的 GD 库的版本,当 fontfile 不以前导 / 开头时,.ttf 将附加到文件名,并且库将尝试沿着库定义的字体路径搜索该文件名。

引用自: http: //php.net/manual/en/function.imagettftext.php

下面是在我的服务器上实际正常工作的工作代码

<?php

// Dynamic value on an image 
header("Content-type: image/jpeg");

error_reporting(E_ALL); 
ini_set('display_errors', TRUE);
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

$data = file_get_contents('https://www.bitstamp.net/api/ticker/', false, $context);
$obj = json_decode($data);

$price = round((40/($obj->{'last'})),3);
$image = imagecreatefrompng("price.png");
$color = ImageColorAllocate($image, 0, 0, 255);

// Calculate horizontal alignment for the value.
$BoundingBox1 = imagettfbbox(13, 0, './ITCKrist.TTF', $price);
$boyX = ceil((125 - $BoundingBox1[2]) / 2);

// Write value.
imagettftext($image, 13, 0, $boyX+25, 92, $color, './ITCKrist.TTF', $price);

// Return output.
ImageJPEG($image, NULL, 93);
ImageDestroy($image);
?>
于 2013-08-20T18:39:08.677 回答