Furtano
Furtano

Reputation: 375

Why isn't a picture drawn? (PHP)

Why doesn't my class draw a picture? If i make it a only function it runs, but in class it doesnt work :(. I am new in PHP classes (Java classes is not new for me).

<?php

class Schild
{

    public function __construct(){
        $text = $_GET['text'];
        $picture = imagecreatefrompng("bild.png");
        $pika = imagecreatefromjpeg("pika.jpg");
        $pika_size = getimagesize("pika.jpg");
    }

    public function drawPicture()
    {
        $im = imagecolorallocate ($picture, 255, 0, 255);
        imagettftext($picture, 111, 0, 100, 100,$im , "Marmellata(Jam)_demo.ttf", $text);

        # int ImageCopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )
        imagecopy($picture, $pika, 50, 50, 0, 0, $pika_size[0], $pika_size[1]);

        $zufall = rand(1,99999999);

        #header("Content-Type: image/jpeg");
        imagejpeg($picture);
        imagedestroy($picture);

    }
}

$schild1 = new Schild();
$schild1->drawPicture();
?>

Upvotes: 0

Views: 77

Answers (1)

Brandon - Free Palestine
Brandon - Free Palestine

Reputation: 16676

<?php

class Schild
{
    protected $picture;
    protected $pika;
    protected $pika_size;
    protected $text;

    public function __construct(){
        $this->text = $_GET['text'];
        $this->picture = imagecreatefrompng("bild.png");
        $this->pika = imagecreatefromjpeg("pika.jpg");
        $this->pika_size = getimagesize("pika.jpg");
    }

    public function drawPicture()
    {
        $im = imagecolorallocate ($this->picture, 255, 0, 255);
        imagettftext($this->picture, 111, 0, 100, 100,$im , "Marmellata(Jam)_demo.ttf", $this->text);

        # int ImageCopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )
        imagecopy($this->picture, $this->pika, 50, 50, 0, 0, $this->pika_size[0], $this->pika_size[1]);

        $zufall = rand(1,99999999);

        #header("Content-Type: image/jpeg");
        imagejpeg($this->picture);
        imagedestroy($this->picture);

    }
}

$schild1 = new Schild();
$schild1->drawPicture();
?>

The problem is you are declaring variables in __construct, but they are local variables. As soon as __construct() finishes executing, it deletes all of the local variables. You must declare them as CLASS variables using the $this keyword, so that they are accessible to your other function.

Upvotes: 3

Related Questions