问题
Been searching for a while and can't seem to get through this. I'm (attempting) to learn php-gd, but for some reason no matter what, even by using ready-to-go code snippets, all I get when the file is run is a small, maybe 20x20px box with a plain border. Looked through phpinfo(); and gd is running fine, and I can't seem to find any errors with the code, any ideas??
<?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);
?>
回答1:
You're seeing that blank square because there's an error that's being suppressed due to the Content-Type header. Try removing the header to see what the error is, or look in your error log.
Also, if you're learning PHP/GD I'd recommend taking a look into a library I wrote that effectively wraps many of GDs functions into a more user-friendly API: SimpleImage
This library can save you a lot of time, code, and tears.
回答2:
Try this code and it should work fine
<?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);
?>
but if you are upto more complex image manipulation tasks then you should focus on a good GD wrapper which makes things easy for you, one I recommend is ImageArtist written by me.
here is the same code in 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();
来源:https://stackoverflow.com/questions/35516499/php-gd-empty-box