【问题标题】:PHP: How can I get the size in bytes of dynamically generated image in php? [duplicate]PHP:如何在 php 中获取动态生成的图像的字节大小? [复制]
【发布时间】:2013-01-31 23:11:04
【问题描述】:

可能重复:
How to get image resource size in bytes with PHP and GD?

是否可以使用 php 获取对象 $image 的文件大小(不是图像大小尺寸)?我想将此添加到我的“Content-Length:”标题中。

$image = imagecreatefromjpeg($reqFilename);

【问题讨论】:

标签: php size filesize


【解决方案1】:

我认为这应该可行:

$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_ 部分,但如果文件已经存储在磁盘上,只需执行filesize() 就可以了。如果他在将图像发送到浏览器之前会调整大小、裁剪或进行其他操作,那么您的解决方案显然是最好的=)
  • 这取决于他显示的是哪个图像。如果不是原版,那么文件大小会有所不同,因为gd会重新压缩jpeg...
  • 我需要在“imagejpeg($new_image);”之前设置标题
  • 是的,即使是 100% 质量...它会输出不同的文件大小。
  • 为什么?在输出缓冲期间不发送标头。 @Krister:无法回答,因为我没有测试过。我会假设它确实
【解决方案2】:

您可以为此使用filesize()

 // 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);

【讨论】:

  • 只需添加一个注释,动态生成的图像应先存储在服务器上的文件中,以便在将其发送到客户端之前使用filesize
  • 只会获取存储图像的大小。但是如果我修改图像怎么办......大小会改变。
  • 我需要在“imagejpeg($new_image);”之前设置标题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 2017-01-07
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多