html - 是否可以在不下载整个图像的情况下检测 URL 中图像的尺寸?

标签 html image parsing html-parsing image-extraction

给定一个包含新闻文章的 HTML 页面,我试图从文章中检测相关图像。为此,我正在查看图像的大小(如果它们太小,则可能是导航元素),但我不想下载每张图像。

有没有办法在不下载完整图像的情况下获取图像的宽度和高度?

最佳答案

不知道它是否会帮助您加快申请速度,但可以做到。查看这两篇文章:

http://www.anttikupila.com/flash/getting-jpg-dimensions-with-as3-without-loading-the-entire-file/对于 JPEG

http://www.herrodius.com/blog/265对于 PNG

它们都是针对 ActionScript 的,但该原则当然也适用于其他语言。

我使用 C# 制作了一个示例。它不是最漂亮的代码,它只适用于 JPEG,但也可以很容易地扩展到 PNG:

var request = (HttpWebRequest) WebRequest.Create("http://unawe.org/joomla/images/materials/posters/galaxy/galaxy_poster2_very_large.jpg");
using (WebResponse response = request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
{
    int r;
    bool found = false;
    while (!found && (r = responseStream.ReadByte()) != -1)
    {
        if (r != 255) continue;

        int marker = responseStream.ReadByte();

        // App specific
        if (marker >= 224 && marker <= 239)
        {
            int payloadLengthHi = responseStream.ReadByte();
            int payloadLengthLo = responseStream.ReadByte();
            int payloadLength = (payloadLengthHi << 8) + payloadLengthLo;
            for (int i = 0; i < payloadLength - 2; i++)
                responseStream.ReadByte();
        }
        // SOF0
        else if (marker == 192)
        {
            // Length of payload - don't care
            responseStream.ReadByte();
            responseStream.ReadByte();

            // Bit depth - don't care
            responseStream.ReadByte();

            int widthHi = responseStream.ReadByte();
            int widthLo = responseStream.ReadByte();
            int width = (widthHi << 8) + widthLo;

            int heightHi = responseStream.ReadByte();
            int heightLo = responseStream.ReadByte();
            int height = (heightHi << 8) + heightLo;

            Console.WriteLine(width + "x" + height);
            found = true;
        }
    }
}

编辑: 我不是 Python 专家,但这篇文章似乎描述了一个 Python 库(最后一个示例):http://effbot.org/zone/pil-image-size.htm

关于html - 是否可以在不下载整个图像的情况下检测 URL 中图像的尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4983797/

相关文章:

html - 如何在特定 div 内的表内选择第一个 TD

php - 我能否以编程方式确定 PNG 是否为动画?

c - 如何在 C 中解析带引号分隔字段的 CSV?

html - HTML 是否将解析的 CSS 结果作为内联样式包含在内?

objective-c - 如何使用 Objective-C 解析 JSON?

html - 图像中间居中文本

jquery - 单选按钮值返回未定义

html - 如何正确显示和居中对齐我的响应式 YouTube 视频?

javascript - 使用 JavaScript 为 HTML 背景图 block 随机选择图像

允许图像双线性变换的Java库