本文實例講述了php實現高效獲取圖片尺寸的方法。分享給大家供大家參考。具體分析如下:
php 獲取圖片尺寸的方法我們可以使用 getimagesize 獲取圖片尺寸,但是效率是很低的,首先需要獲取整個的圖片信息,然後再進行操作,下面的例子更科學算法更好,我們一起來看看吧.
方法可以用於快速獲取圖片尺寸信息,獲取JPEG格式圖片的尺寸信息,並且不需要下載讀取整個圖片,經測試這個函數不是對所有JPEG格式的圖片都有效.
1.獲取JPEG格式圖片的尺寸信息,代碼如下:
復制代碼 代碼如下:<?php
/*
* http://www.bkjia.com
*/
// 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;
}
?>
2.實例代碼如下:
復制代碼 代碼如下:$url='http://www.xxxx.com/images/1331189004_28093400.jpg';
$image_content = file_get_contents($url);
$image = imagecreatefromstring($image_content);
$width = imagesx($image);
$height = imagesy($image);
echo $width.'*'.$height."nr";
希望本文所述對大家的PHP程序設計有所幫助。