Image generating problem with PHP form a class
i wrote this code:
class Generate{
private $canvas;
function __construct($width, $height){
$this->canvas = imagecreatetruecolor($width, $height);
}
public function bg($r=0,$g=0,$b=0){
$color = imagecolorallocate($this->canvas, $r, $g, $b);
imagefill($this->canvas, 0, 0, $color);
}
public function gen(){
header('Content-Type: i开发者_开发技巧mage/png');
imagepng($this->canvas, NULL, 9);
imagedestroy($this->canvas);
}
}
and called it with this:
$G = new Generate(100, 100);
$G->bg(255, 255, 255);
$G->gen();
its generating image fine when i comment out the header in the gen() function and set it to save the image. Like this:
imagepng($this->canvas, 'img.png', 9);
but i want it to send the header(output the image) but it gives me an error. can someone please tell me what i'm doing wrong? can you even send headers with-in a PHP class?
this code works fine when i don't use OOP
The answer to your question is yes, you can. You can send headers at any time before you send any output to the client, which I suspect is what your issue is.
You can also check the encoding that you're saving your file in. If you are saving your file as UTF-8, make sure you save it without a byte order mark. This counts as output, and will always be the first character in your file meaning any call to header()
will generate a warning.
The code works perfectly for me when I run it as you posted it; are you sure that you aren't just losing your 100x100 white image on a white background? Try changing the color to, say, 127,255,255
(a lovely aqua) and see if it shows up.
精彩评论