php高效快速获取图片尺寸的方法

在 php 获取图片尺寸的方法我们可以使用 getimagesize 获取图片尺寸的效率是很低的,首先需要获取整个的图片信息,然后再进行操作,下面的例子更科学算法更好,我们一起来看看吧.

方法可以用于快速获取图片尺寸信息,获取JPEG格式图片的尺寸信息,并且不需要下载读取整个图片,经测试这个函数不是对所有JPEG格式的图片都有效.

1.获取JPEG格式图片的尺寸信息,代码如下:

  1. <?php
  2. /*
  3. * http://www.phpfensi.com
  4. */
  5. // Retrieve JPEG width and height without downloading/reading entire image.
  6. function getjpegsize($img_loc) {
  7. $handle = fopen($img_loc, "rb") or die("Invalid file stream.");
  8. $new_block = NULL;
  9. if(!feof($handle)) {
  10. $new_block = fread($handle, 32);
  11. $i = 0;
  12. if($new_block[$i]=="xFF" && $new_block[$i+1]=="xD8" && $new_block[$i+2]=="xFF" && $new_block[$i+3]=="xE0") {
  13. $i += 4;
  14. 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") {
  15. // Read block size and skip ahead to begin cycling through blocks in search of SOF marker
  16. $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
  17. $block_size = hexdec($block_size[1]);
  18. while(!feof($handle)) {
  19. $i += $block_size;
  20. $new_block .= fread($handle, $block_size);
  21. if($new_block[$i]=="xFF") {
  22. // New block detected, check for SOF marker
  23. $sof_marker = array("xC0", "xC1", "xC2", "xC3", "xC5", "xC6", "xC7", "xC8", "xC9", "xCA", "xCB", "xCD", "xCE", "xCF");
  24. if(in_array($new_block[$i+1], $sof_marker)) {
  25. // SOF marker detected. Width and height information is contained in bytes 4-7 after this byte.
  26. $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];
  27. $unpacked = unpack("H*", $size_data);
  28. $unpacked = $unpacked[1];
  29. $height = hexdec($unpacked[6] . $unpacked[7] . $unpacked[8] . $unpacked[9]);
  30. $width = hexdec($unpacked[10] . $unpacked[11] . $unpacked[12] . $unpacked[13]);
  31. return array($width, $height);
  32. } else {
  33. // Skip block marker and read block size
  34. $i += 2;
  35. $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
  36. $block_size = hexdec($block_size[1]);
  37. }
  38. } else {
  39. return FALSE;
  40. }
  41. }
  42. }
  43. }
  44. }
  45. return FALSE;
  46. }
  47. ?>

2.实例代码如下:

  1. $url='http://www.phpfensi.com/images/201203/08/1331189004_28093400.jpg';
  2. $image_content = file_get_contents($url);
  3. $image = imagecreatefromstring($image_content);
  4. $width = imagesx($image);
  5. $height = imagesy($image);
  6. echo $width.'*'.$height."nr";