This article is an example of how to achieve an efficient way to obtain picture size in PHP. Share to everyone for your reference. The specific analysis is as follows:
PHP to get the image size of the method we can use getimagesize to get picture size, but the efficiency is very low, first need to get the entire picture information, and then to operate, the following example more scientific algorithm better, let's take a look.
Method can be used to quickly get picture size information, get the size information of JPEG format picture, and do not need to download and read the whole picture, after testing this function is not valid for all pictures in JPEG format.
1. Get the dimension information of JPEG format picture, the code is as follows:
Copy Code code as follows:
<?php
/*
* Http://www.jb51.net
*/
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 into 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 [a]. $unpacked [one]. $unpacked [A] $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. The example code is as follows:
Copy Code code as follows:
$url = ' yun_qi_img/index.html ';
$image _content = file_get_contents ($url);
$image = imagecreatefromstring ($image _content);
$width = Imagesx ($image);
$height = Imagesy ($image);
echo $width. ' * '. $height. " NR ";
I hope this article will help you with your PHP program design.