【问题标题】:How to get image resource size in bytes with PHP and GD?如何使用 PHP 和 GD 获取图像资源大小(以字节为单位)?
【发布时间】:2010-10-26 12:03:51
【问题描述】:

我正在使用 php gd 调整图像大小。结果是我想上传到 Amazon S3 的图像资源。如果我先将图像存储在磁盘上,效果很好,但我想直接从内存上传它们。如果我只知道图像的字节大小,这是可能的。

有没有办法获取 gd 图片资源的大小(以字节为单位)?

【问题讨论】:

    标签: php image gd


    【解决方案1】:

    您可以使用 PHP 的 memory i/o stream 将图像保存到并随后获取以字节为单位的大小。

    你要做的是:

    $img = imagecreatetruecolor(100,100);
    // do your processing here
    // now save file to memory
    imagejpeg($img, 'php://memory/temp.jpeg'); 
    $size = filesize('php://memory/temp.jpeg');
    

    现在你应该知道尺寸了

    我不知道任何 (gd) 方法可以获取图像资源的大小。

    【讨论】:

    • 问题是gd 函数需要一个路径而不是文件资源来写入。不过,这应该与 output buffering 一起使用。
    • @deceze:您应该能够提供如下路径:php://memory/resource=img.jpeg
    • 啊,不错!这将使用双倍的内存,所以它不是最佳选择,而是一个不错的选择:)
    【解决方案2】:

    我不能用imagepng在php://memory上写,所以我用ob_start(), ob_get_content() end ob_end_clean()

    $image = imagecreatefrompng('./image.png'); //load image
    // do your processing here
    //...
    //...
    //...
    ob_start(); //Turn on output buffering
    imagejpeg($image); //Generate your image
    
    $output = ob_get_contents(); // get the image as a string in a variable
    
    ob_end_clean(); //Turn off output buffering and clean it
    echo strlen($output); //size in bytes
    

    【讨论】:

    • 为什么不像@JonathanWren 建议的那样使用ob_get_length
    【解决方案3】:

    这也有效:

    $img = imagecreatetruecolor(100,100);
    
    // ... processing
    
    ob_start();              // start the buffer
    imagejpeg($img);         // output image to buffer
    $size = ob_get_length(); // get size of buffer (in bytes)
    ob_end_clean();          // trash the buffer
    

    现在$size 将以字节为单位显示您的大小。

    【讨论】:

    • 谢谢。这对我有帮助,因为我需要一种无需上传即可确定文件大小的方法。
    【解决方案4】:

    您可能会查看以下答案以寻求帮助。它适用于 php.ini 中的通用内存更改。 虽然由于可能涉及开销,但它可能更多是一种估计。

    Getting size of PHP objects

    【讨论】:

      【解决方案5】:

      将图像文件以所需格式保存到 tmp 目录,然后使用 filesize() http://php.net/manual/de/function.filesize.php 将其从磁盘上传到 S3。

      【讨论】:

      • 这里是英文版:php.net/manual/en/function.filesize.php :)
      • 在磁盘上保存临时文件正是我在这里试图避免的。
      • 为什么?这不是什么性能问题,而且可以节省大量内存。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      • 2011-01-13
      • 1970-01-01
      • 2015-11-17
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      相关资源
      最近更新 更多