PHP GD - 空盒子

时间:2016-02-19 22:46:52

标签: php gd

一直在寻找,但似乎无法解决这个问题。我(尝试)学习php-gd,但出于某种原因无论如何,即使使用现成的代码片段,我在文件运行时得到的只是一个小的,可能是20x20px的盒子,带有简单的边框。透过phpinfo()看;和gd运行正常,我似乎无法找到代码中的任何错误,任何想法??

<?php
$redimg = imagecreatetruecolor(100, 100);
$image = imagecreatefrompng('overlay.png');

// sets background to red
$red = imagecolorallocate($redimg, 255, 0, 0);
imagefill($redimg, 0, 0, $red);

imagecopymerge($image, $redimg, 0, 0, 0, 0, 100, 100, 75);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
imagedestroy($redimg);

?>

2 个答案:

答案 0 :(得分:1)

您看到该空白正方形,因为有一个错误因Content-Type标头而被抑制。尝试删除标题以查看错误,或查看错误日志。

此外,如果您正在学习PHP / GD,我建议您查看我编写的库,该库有效地将许多GD功能包装到更加用户友好的API中:SimpleImage < / p>

这个库可以节省大量的时间,代码和眼泪。

答案 1 :(得分:0)

尝试此代码,它应该可以正常工作

<?php
 $redimg = imagecreatetruecolor(100, 100);
 $red = imagecolorallocate($redimg, 255, 0, 0);
 imagefill($redimg, 0, 0, $red);

 $image = imagecreatefrompng('./cover.png');
 imagesavealpha($image,true);

 imagecopyresampled($redimg, $image, 0, 0, 0, 0, 100, 100, 
 imagesx($image), imagesy($image));

 /** your code for writing to the response might not work in localhost 
 because apache directly write entaire bytes to the response and most 
 browsers do not like that. but it should surly work in the remote host **/
 ob_start();
 imagepng($redimg);
 $base64 = base64_encode(ob_get_clean());
 $url = "data:image/png;base64,$base64";
 echo "<body style='background: green' ><img src='$url' /></body>";

imagedestroy($image);
imagedestroy($redimg);

?>

但如果您要处理更复杂的图像处理任务,那么您应该专注于一个好的GD包装器,这样可以让您轻松实现,我建议使用ImageArtist编写。

这是ImageArtist中的相同代码。

$img = new Overlay(100,100,new Color(255,0,0));
$img2 = new Image("./cover.png");
$img2->resize(100,100);

$img = $img->merge($img2,0,0);
$img->dump();