我知道什么是函数,类,方法等基础知识。然而,我完全不知道下面的代码究竟是什么来读取图像,我在某处阅读它,我们必须阅读图像首先是二进制格式。我对php如何读取图像并加载它以供阅读的过程感到困惑。我想知道这个类中每个代码的功能以及代码实际发生的情况。
代码:
class Image {
function __construct($filename) {
//read the image file to a binary buffer
$fp = fopen($filename, 'rb') or die("Image $filename doesn't exist");
$buf = '';
while(!feof($fp))
$buf .= fgets($fp, 4096);
//create image
imagecreatefromstring($buf);
}
}
当我使用语法$image = new Image("pic.jpg");
实例化对象图像时,它不会在html中打印图像,变量$ image实际上是什么,如果我想在html中打印该图像我应该做什么
更新:
仅供参考:我理解PHP和HTML,因为我正在尝试用PHP学习OOP,因为这个特定的代码没有被我理解,所以我想问你们,我非常感谢你的回答,如果您可以尝试解释代码而不是让我尝试不同的代码,我将感激不尽。
我的关注纯粹是出于学习目的,我没有在任何地方实施。
答案 0 :(得分:2)
在HTML中,您需要做的就是在<img>
标记中引用该文件。
<img src="/path/to/image/image.jpg" width="600" height="400" alt="Image Name" />
源必须是图像的URL,相对于您的Web服务器根目录。
至于代码,你提出来了。这对于HTML使用来说是完全没有必要的,并且对于PHP中的标准图像使用也是不必要的,因为有直接的方法从文件加载图像,imagecreatefromjpeg()例如用于JPEG文件。
按照目前的情况,Image
类的构造函数接受一个文件名,打开该文件并将整个内容作为二进制数据读入字符串$buf
,一次读取4096个字节。然后它调用imagecreatefromstring($buf)
将文件数据转换为图像资源,然后可以在PHP中使用PHP GD image handling functions进一步使用。
正如我所说,如果您只想在HTML中显示现有图像,那么这一切都不是特别相关。这些命令专为图像处理,检查和创建而设计。
答案 1 :(得分:1)
PHP的imagecreate*
函数返回一个资源。如果要将其发送到客户端,则必须设置相应的标题,然后发送原始图像:
header('Content-Type: image/jpeg');
imagejpeg($img);
有关详细信息,请参阅GD and Image Functions documentation。
答案 2 :(得分:1)
class Image
{
public $source = '';
function __construct($filename)
{
$fp = fopen($filename, 'rb') or die("Image $filename doesn't exist");
$buf = '';
while(!feof($fp))
{
$buf .= fgets($fp, 4096);
}
$this->source = imagecreatefromstring($buf);
}
}
$image = new Image('image.jpg');
/* use $image->source for image processing */
header('Content-Type: image/jpeg');
imagejpeg($image->source);
答案 3 :(得分:1)
您的$image
将包含Image
类的实例。
您的constructor会尝试打开$filename
。如果那是不可能的,脚本将死/终止并显示错误消息。如果可以打开$filename
,则会将文件读入$buf
变量,并创建GD图像资源。
由于多种原因,代码不是最理想的:
imagecreatefromstring
创建的GD资源未分配给property of the Image class。这意味着整个过程毫无意义,因为资源在创建后将会丢失。构造函数中完成的工作已丢失。
调用die
将终止脚本。没有办法解决这个问题。 throw an Exception to let the developer decide whether s/he wants the script to terminate or catch and handle this situation.
读取fopen
和fread
的文件,但file_get_contents
is the preferred way to read the contents of a file into a string.如果您的操作系统支持,它将使用内存映射技术来提高性能。
更好的方法是使用
class Image
{
protected $_gdResource;
public function loadFromFile($fileName)
{
$this->_gdResource = imagecreatefromstring(
file_get_contents($fileName)
);
if(FALSE === $this->_gdResource) {
throw new InvalidArgumentException(
'Could not create GD Resource from given filename. ' .
'Make sure filename is readable and contains an image type ' .
'supported by GD'
);
}
}
// other methods working with $_gdResource …
}
然后你可以做
$image = new Image; // to create an empty Image instance
$image->loadFromFile('pic.jpg') // to load a GD resource
答案 4 :(得分:0)
如果您只想显示图像,以上所有内容都无关紧要。您只需要写出一个HTML图像标记,例如
echo '<img src="pic.jpg" />';
就是这样。
您提供的代码使用GD库为操作加载图像需要非常长且不方便的方法;这几乎肯定不是你想要做的,但如果你这样做,那么你可以改用imagecreatefromjpeg。