C#得到Web图像的宽度/高度,而无需下载整个文件?宽度、图像、高度、文件

2023-09-03 17:28:09 作者:隱身→垨候

我相信,JPG格式,宽度和高度信息中的前几个存储字节。什么是获取此信息给予绝对URI?最简单的方法

I believe with JPGs, the width and height information is stored within the first few bytes. What's the easiest way to get this information given an absolute URI?

推荐答案

首先,你可以使用范围头请求的第一个几百个字节的图像。

First, you can request the first hundred bytes of an image using the Range header.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Set(HttpRequestHeader.UserAgent, "Range: bytes=0-100");

接下来,你需要去code。该 UNIX 文件命令具有共同格式的表格,并将重要信息的位置。我建议安装Cygwin和采取看看的/ usr /共享/文件/魔术

有关 GIF png格式的,你可以很容易地获得图像的尺寸由前32个字节。然而,对于JPEG文件,@Andrew是正确的,你不能可靠地获取这些信息。你可以计算出它是否有一个缩略图,缩略图的大小。

For gif's and png's, you can easily get the image dimensions from the first 32 bytes. However, for JPEGs, @Andrew is correct in that you can't reliably get this information. You can figure out if it has a thumbnail, and the size of the thumbnail.

在获得实际的JPEG大小,您需要扫描帧标记的启动。不幸的是,我们不能可靠地确定这将是提前,和缩略图可以将其推几千字节到文件中。

The get the actual jpeg size, you need to scan for the start of frame tag. Unfortunately, one can't reliably determine where this is going to be in advance, and a thumbnail could push it several thousand bytes into the file.

我会建议使用范围要求得到第32个字节。这将让你确定文件类型。在此之后,如果它是一个JPEG,然后下载整个文件,并使用库来获得尺寸的信息。

I'd recommend using the range request to get the first 32 bytes. This will let you determine the file type. After which, if it's a JPEG, then download the whole file, and use a library to get the size information.