php怎么获取图片信息,php 如何高效获取远程图片信息?

As noted below, getimagesize will download the entire image before it checks for the requested information. This is extremely slow on large images that are accessed remotely. Since the width/height is in the first few bytes of the file, there is no need to download the entire file. I wrote a function to get the size of a JPEG by streaming bytes until the proper data is found to report the width and height:

// Retrieve JPEG width and height without downloading/reading entire image.

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;

}

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值