PHP:如何在PHP中获得动态生成的图像的大小(以字节为单位)?
可能重复:PHP:如何在PHP中获得动态生成的图像的大小(以字节为单位)?,php,size,filesize,Php,Size,Filesize,可能重复: 是否可以使用php获取object$image的文件大小(而不是图像大小维度)?我想将此添加到我的“内容长度:”标题中 您可以使用以下方法: // returns the size in bytes of the file $size = filesize($reqFilename); 当然,上述方法仅适用于已调整大小的图像是存储在磁盘上的图像的情况。如果在调用imagecreatefromjpeg()后要调整图像大小,则应使用@one Trick Ponys解决方案并执行以
是否可以使用php获取object$image的文件大小(而不是图像大小维度)?我想将此添加到我的“内容长度:”标题中 您可以使用以下方法:
// returns the size in bytes of the file
$size = filesize($reqFilename);
当然,上述方法仅适用于已调整大小的图像是存储在磁盘上的图像的情况。如果在调用imagecreatefromjpeg()
后要调整图像大小,则应使用@one Trick Ponys解决方案并执行以下操作:
// load original image
$image = imagecreatefromjpeg($filename);
// resize image
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// get size of resized image
ob_start();
// put output for image in buffer
imagejpeg($new_image);
// get size of output
$size = ob_get_length();
// set correct header
header("Content-Length: " . $size);
// flush the buffer, actually send the output to the browser
ob_end_flush();
// destroy resources
imagedestroy($new_image);
imagedestroy($image);
我认为这应该奏效:
$img = imagecreatefromjpeg($reqFilename);
// capture output
ob_start();
// send image to the output buffer
imagejpeg($img);
// get the size of the o.b. and set your header
$size = ob_get_length();
header("Content-Length: " . $size);
// send it to the screen
ob_end_flush();
+1对于
ob\uu
部分,但是如果文件已经存储在磁盘上,只需执行filesize()
即可。如果他在将图像发送到浏览器之前调整大小、裁剪或进行其他操作,那么您的解决方案显然是最佳的=)这取决于他显示的图像。如果它不是原始的,那么文件大小将不同,因为gd将重新压缩jpeg…我需要在“imagejpeg($new_image);”之前设置头,即使是100%的质量。。。它将输出不同的文件大小。为什么?在输出缓冲期间不发送头@克里斯特:我不能回答这个问题,因为我还没有测试过。我假设它没有添加一个注释,动态生成的图像应该首先存储在服务器上的一个文件中,以便在发送到客户端之前使用filesize
。这将只获取存储图像的大小。但是,如果我修改图像。。。大小将更改。我需要在“imagejpeg($new_image);”之前设置标题。您应该阅读有关类似ob_start()
,ob_clean()
,ob_flush()
等的更多信息
$img = imagecreatefromjpeg($reqFilename);
// capture output
ob_start();
// send image to the output buffer
imagejpeg($img);
// get the size of the o.b. and set your header
$size = ob_get_length();
header("Content-Length: " . $size);
// send it to the screen
ob_end_flush();