使用php输出图像对象内容

时间:2014-03-16 20:16:41

标签: php

初学者问题:

<?php

class Image {

    // class atributes (variables)
    private $image;
    private $width;
    private $height;
    private $mimetype;

    function __construct($filename) {

        // read the image file to a binary buffer
        $fp = fopen($filename, 'rb') or die("Image '$filename' not found!");
        $buf = '';
        while (!feof($fp))
        $buf .= fgets($fp, 4096);

        // create image and assign it to our variable
        $this->image = imagecreatefromstring($buf);

        // extract image information
        $info = getimagesize($filename);
        $this->width = $info[0];
        $this->height = $info[1];
        $this->mimetype = $info['mime'];
    }

    public function display() {
        header("Content-type: {$this->mimetype}");
        switch ($this->mimetype) {
            case 'image/jpeg': imagejpeg($this->image);
                break;
            case 'image/png': imagepng($this->image);
                break;
            case 'image/gif': imagegif($this->image);
                break;
        }
        //exit;
    }

}

$image = new Image("image.jpg"); // If everything went well we have now read the image
?>

如果我var_dump图像变量,我得到这个:

object(Image)#1 (4) {
  ["image":"Image":private]=>
  resource(4) of type (gd)
  ["width":"Image":private]=>
  int(600)
  ["height":"Image":private]=>
  int(900)
  ["mimetype":"Image":private]=>
  string(10) "image/jpeg"
}

我知道我可以通过调用$ image-&gt; display()来输出内容;但是如何在没有显示方法的情况下输出该对象的内容?

在课堂上下文中尝试了这一点:

   $image = new Image("image.jpg");
     header("Content-type: image/jpeg");
     imagejpeg($image->image);

似乎我在这里丢失了一些东西,因为我一直得到破碎的图像图标。

谢谢!

0 个答案:

没有答案