嗨,我有一个网站,我在其中使用 php GD 库制作图像,我想知道如何获得这些随机大小图像的大小(以 KB 或 MB 为单位)。请任何人知道它。
2 回答
您可以通过执行以下操作获取图像的文件大小:
$image_size_in_bytes = filesize($path_to_image);
要使用 URL 获取图像的文件大小,请使用以下代码:(请注意,您必须安装 cURL 扩展)
<?php
// URL to file (link)
$file = 'http://example.com/file.zip';
$ch = curl_init($file);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
// Contains file size in bytes
$contentLength = (int)$matches[1];
}
?>
在这里阅读更多。
PHP doesn't have a way to get information about the size of a variable, exactly. One way to get around this is by checking memory usage before and after you generate the image for use as an approximation.
Another way would be to build the image, then set the JPEG/GIF/PNG/etc. data to a variable. Use strlen to get the size of that string in bytes, which will be your image size. I'm not sure how to get the string of data from GD without setting up an output buffer, echo-ing the GD variable, then closing and capturing the buffer; the only other output I know of would be to write it to disk. Which brings us to...
Save the image file to a temporary directory, then get the file size with the filesize function. This will be the most accurate, because when you write the image you will also be setting the type of image file to write, which has an effect on the size. It's also going to involve a lot more disk activity on your server.