I'm trying to create a dynamic image generator that also caches the images.
Everything works perfectly, except that for some reason when I save an images and try to display it at the same time, it shows a broken image icon (like: http://cl.ly/image/3K1f0R0n1R0U).
Code sample:
// some string parsing junk happens up here, but removing that didn't change
// what I've been having a problem with
header("Content-type: image/png;");
if(file_exists($fullFileName)){ // serve the file if it already exists
ob_clean();
flush();
readfile($fullFileName);
exit;
} else { // create the file if it doesn't exist
$my_img = imagecreate(200, 80);
$background = imagecolorallocatealpha($my_img, 0, 0, 0, 127);
$line_colour = imagecolorallocatealpha($my_img, $color["r"], $color["g"], $color["b"], $color["a"]);
imagesetthickness($my_img, 1);
imageline($my_img, 30, 45, 165, 45, $line_colour);
//////////////////////////////////////////
// the line that's causing my troubles: //
//////////////////////////////////////////
imagepng($my_img, $fullFileName);
imagecolordeallocate($line_color);
imagecolordeallocate($background);
imagedestroy($my_img);
}
So, the images are created just fine, save just fine, and display exactly like I want when I refresh the page (because it grabs the saved file).
If I switch that darn line above to:
imagepng($my_img);
Then the image shows up fine, but it doesn't save (since I'm not telling it to).
I thought that this topic:
PHP echoing jpeg image fails, but writing same image to file works great. Why?
Sounded similar, but removing the trailing white space still didn't change what's happening. Other threads mentioned it could be a problem with other content being sent before the headers, but there is nothing like that in this file.
Any ideas on what could be going wrong? No errors are being logged, and I'm out of ideas.
Thanks!
-Zach
EDIT:
It was explained that I was destroying my image, which I missed. I ended up using this:
header("Content-type: image/png");
if(!file_exists($fullFileName)) {
$my_img = imagecreate($dashWidth + $dashSpace, $height);
$background = imagecolorallocatealpha($my_img, 0, 0, 0, 127);
$line_colour = imagecolorallocatealpha($my_img, $color["r"], $color["g"], $color["b"], $color["a"]);
imagesetthickness($my_img, 1);
imageline($my_img, 0, $height-1, $dashWidth-1, $height-1, $line_colour);
imagepng($my_img, $fullFileName);
imagecolordeallocate($my_img, $line_color);
imagecolordeallocate($my_img, $background);
}
ob_clean();
flush();
readfile($fullFileName);
exit;
you mean
and also, you are destroying your image, read again the file
because
imagepng($my_img, $fullFileName);
only saves it.