我使用PHP getimagesize()函数来获取远程服务器上图像的文件类型。
在这里查看getimagesize()的PHP文档,http://php.net/manual/en/function.getimagesize.php在注释中指出,该函数首先下载整个文件,然后获取有关该文件的信息。
这条评论还提供了一个替代功能来取代getimagesize(),后者声称只下载第一个字节,直到它获得所需的信息,这比第一次下载整个文件要快。
然而,这个新函数的问题是它被命名为getJpegSize($img_loc),并声称可以处理JPEG文件。既然我的用户显然不会仅限于JPG文件,我很好奇是否有更好的方法来做这件事,既快又适用于其他图像类型?
新函数的代码如下所示。还可以直接链接到注释和代码所在的PHP Docs页面:http://php.net/manual/en/function.getimagesize.php#88793
// Retrieve JPEG width and height without downloading/reading entire image.
// From http://php.net/manual/en/function.getimagesize.php
function getJpegSize($img_loc) {
$handle = fopen($img_loc, "rb") or die("Invalid file stream.");
$new_block = NULL;
if(!feof($handle)) {
$new_block = fread($handle, 32);
$i = 0;
if($new_block[$i]=="\xFF" && $new_block[$i+1]=="\xD8" && $new_block[$i+2]=="\xFF" && $new_block[$i+3]=="\xE0") {
$i += 4;
if($new_block[$i+2]=="\x4A" && $new_block[$i+3]=="\x46" && $new_block[$i+4]=="\x49" && $new_block[$i+5]=="\x46" && $new_block[$i+6]=="\x00") {
// Read block size and skip ahead to begin cycling through blocks in search of SOF marker
$block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
$block_size = hexdec($block_size[1]);
while(!feof($handle)) {
$i += $block_size;
$new_block .= fread($handle, $block_size);
if($new_block[$i]=="\xFF") {
// New block detected, check for SOF marker
$sof_marker = array("\xC0", "\xC1", "\xC2", "\xC3", "\xC5", "\xC6", "\xC7", "\xC8", "\xC9", "\xCA", "\xCB", "\xCD", "\xCE", "\xCF");
if(in_array($new_block[$i+1], $sof_marker)) {
// SOF marker detected. Width and height information is contained in bytes 4-7 after this byte.
$size_data = $new_block[$i+2] . $new_block[$i+3] . $new_block[$i+4] . $new_block[$i+5] . $new_block[$i+6] . $new_block[$i+7] . $new_block[$i+8];
$unpacked = unpack("H*", $size_data);
$unpacked = $unpacked[1];
$height = hexdec($unpacked[6] . $unpacked[7] . $unpacked[8] . $unpacked[9]);
$width = hexdec($unpacked[10] . $unpacked[11] . $unpacked[12] . $unpacked[13]);
return array($width, $height);
} else {
// Skip block marker and read block size
$i += 2;
$block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
$block_size = hexdec($block_size[1]);
}
} else {
return FALSE;
}
}
}
}
}
return FALSE;
}发布于 2015-07-11 11:30:49
每种图像类型都有不同的存储大小的方式。因为您对类型没有任何限制,所以您应该使用getimagesize()并避免添加太多的复杂性(除非您确实需要它)。它将简化您的代码并有助于维护(如果您粘贴的函数中有bug,祝您好运找到它!)
https://stackoverflow.com/questions/31352617
复制相似问题