I'm trying to generate an image using php-gd but the output is only special characters. Did I use the "header('Content-Type: image/png')" correct?
My Image Class:
public function __construct(){
header('Content-Type: image/png');
$this->image = imagecreate(200, 80);
imagecolorallocate($this->image, 150, 150, 150);
$textColor = imagecolorallocate($this->image, 255,255,255);
imagestring($this->image, 28, 50, 55,rand(1000,9999), $textColor);
}
public function generateImage(){
imagepng($this->image);
imagedestroy($this->image);
}
My DefaultController:
/**
* @Route("/display-scorepng", name="scorepng")
*/
public function displayScorePng(){
$test = new ImageController;
return new Response("<h1>Hello World</h1> <br /><img src='" .$test->generateImage(). "' />");
}
Thank you for your reply..
CodePudding user response:
You have confused two different things we might mean by "display an image":
- If you open an image file on your computer, you are looking at just that file. An application will display the image to you, with nothing else. You can open an image file in your web browser, and it will display it in that sense.
- If you have an HTML page, you can have a mixture of text and references to images. Each image that is referenced will be displayed as part of the page, by loading the separate image file and positioning it on the screen relative to other content.
When you call imagepng
, it is "displaying" the image in the first sense - it is generating the actual binary data of the image, to be treated as its own file. But then you call that function mixed up with some HTML, trying to "display" it in the second sense. The result is as though you'd opened an image file in a text editor and pasted the result into the middle of an HTML file.
You need to remove all mention of HTML from this route, and just output the image. It should display exactly the same as if you'd created the image in MS Paint and uploaded it. Then you can reference it in an HTML page by URL, just like you would a "real" image you'd uploaded (to the browser, it's just as real).
/**
* @Route("/display-scorepng", name="scorepng")
*/
public function displayScorePng(){
$test = new ImageController;
// This function doesn't return anything, it just outputs:
$test->generateImage();
// Since the output is already done, we could just stop here
exit;
}
Somewhere else completely:
<p>This is an image: <img src="/display-scorepng" alt="something useful for blind folks"></p>