用php输出图像对象内容
初学者的问题:用php输出图像对象内容,php,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
<?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
?>
我知道我可以通过调用$image->display()输出内容;但是如果没有display方法,我如何输出这个对象的内容呢
在类上下文之外尝试此操作:
$image = new Image("image.jpg");
header("Content-type: image/jpeg");
imagejpeg($image->image);
似乎我在这里错过了一些东西,因为我一直都在得到破碎的图像图标
谢谢大家! 如果它有一个方法来显示您希望以另一种方式执行此操作的原因是什么?
$image
属性是私有的,因此不能在类外访问。如果您想获得它,可以修改(或扩展)该类以添加访问器公共函数getImage(){return$this->image;}
实际上,前面的注释并不完全准确。您无法从扩展类中检索它,因为它是私有的
而不是受保护的
。它必须来自此图像
类
$image = new Image("image.jpg");
header("Content-type: image/jpeg");
imagejpeg($image->image);