如何在不下载的情况下确定图像的大小(完整)? [英] How to determine the size of an image without downloading it (in full)?

查看:133
本文介绍了如何在不下载的情况下确定图像的大小(完整)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望获得远程托管JPG的尺寸,宽度和高度。我已经看到了如何通过下载完整的图像来实现这一点。

I'm looking to get the dimensions, width and height, of a remotely hosted JPG. I have seen how it is possible to do this by downloading the full image.

然而,如果我能通过下载足够只是得到这个来做到这一点将是理想的信息。

However, it would be ideal if I could do this by downloading only enough to just get this information.

典型的图片尺寸为200K,开头只需几张K 可能就可能足够JPG了:

Typical images are 200K in size and reading in just a few K might at the beginning might be enough for JPGs:

curl_setopt($ ch,CURLOPT_RANGE,0-4096);

作为参考,我已经按照这些答案/评论但无济于事(尽管它们可能在正确的轨道上):

For reference, I've followed these answers/comments but to no avail (though they might be on the right track):

  • Get image dimensions with Curl
  • Alternative to CURLOPT_RANGE to grab a specific section

有没有人能够将这些碎片拼凑在一起(没有ImageMagick)?

Has anyone been able to put the pieces together (withor without ImageMagick)?

解决方案

我设法回答了我自己的问题,并且我已经包含了PHP代码片段。

I managed to answer my own question and I've included the PHP code snippet.

唯一的缺点(对我来说)至少)是在使用 getImageSize 读取尺寸之前将部分图像下载写入文件系统。

The only downside (for me at least) is that this writes the partial image download to the file-system prior to reading in the dimensions with getImageSize.

对我来说, 10240 字节是检查大小为200到400K的jpg图像的安全限制。

For me 10240 bytes is the safe limit to check for jpg images that were 200 to 400K in size.

function remoteImage($url){
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    curl_setopt($ch, CURLOPT_RANGE, "0-10240");

    $fn = "partial.jpg";
    $raw = curl_exec($ch);
    $result = array();

    if(file_exists($fn)){
        unlink($fn);
    }

    if ($raw !== false) {

        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($status == 200 || $status == 206) {

            $result["w"] = 0;
            $result["h"] = 0;

            $fp = fopen($fn, 'x');
            fwrite($fp, $raw);
            fclose($fp);

            $size = getImageSize($fn);

            if ($size===false) {
            //  Cannot get file size information
            } else {
            //  Return width and height
                list($result["w"], $result["h"]) = $size;
            }

        }
    }

    curl_close ($ch);
    return $result;
}

这篇关于如何在不下载的情况下确定图像的大小(完整)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆