我从指定网址的网页获取一些图片,我想获取它们的高度和宽度。我正在使用这样的东西:
Stream str = null;
HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(ImageUrl);
HttpWebResponse wRes = (HttpWebResponse)(wReq).GetResponse();
str = wRes.GetResponseStream();
var imageOrig = System.Drawing.Image.FromStream(str);
int height = imageOrig.Height;
int width = imageOrig.Width;
我主要担心的是图像文件实际上可能非常大,
有什么我可以做的吗?即指定仅获取小于 1mb 的图像? 或者是否有更好的替代方法从网页获取图像的尺寸?
谢谢
最佳答案
一些(全部?)图像格式在文件头中包含宽度和高度属性。您可以只请求足够的字节来读取 header ,然后自己解析它们。您可以向 Web 请求添加一个范围 header ,该 header 仅请求图像文件的前 50 个字节(50 个只是一个示例,您可能需要更少):
wReq.AddRange(0, 50);
我想这只有在您知道您正在使用的格式包含此数据时才有效。
编辑:看来我之前误解了 AddRange
方法。现在修好了。我还继续使用 this documentation 获取 png 的宽度和高度来测试它.
static void Main(string[] args)
{
string imageUrl = "http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
byte[] pngSignature = new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 };
HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(imageUrl);
wReq.AddRange(0, 30);
WebResponse wRes = wReq.GetResponse();
byte[] buffer = new byte[30];
int width = 0;
int height = 0;
using (Stream stream = wRes.GetResponseStream())
{
stream.Read(buffer, 0, 30);
}
// Check for Png
// 8 byte - Signature
// 4 byte - Chunk length
// 4 byte - Chunk type - IDHR (Image Header)
// 4 byte - Width
// 4 byte - Height
// Other stuff we don't care about
if (buffer.Take(8).SequenceEqual(pngSignature))
{
var idhr = buffer.Skip(12);
width = BitConverter.ToInt32(idhr.Skip(4).Take(4).Reverse().ToArray(), 0);
height = BitConverter.ToInt32(idhr.Skip(8).Take(4).Reverse().ToArray(), 0);
}
// Check for Jpg
//else if (buffer.Take(?).SequenceEqual(jpgSignature))
//{
// // Do Jpg stuff
//}
// Check for Gif
//else if (etc...
Console.WriteLine("Width: " + width);
Console.WriteLine("Height: " + height);
Console.ReadKey();
}
关于c# - 在网络上获取图像的尺寸 - 避免内存占用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4620923/