获取远程图像尺寸

给定图像的URL(而不是图像本身),获得它的尺寸最有效的是什么? 我想更改图像标记( )中的高度和宽度属性,如果它大于200×200。 但是,如果它小于那个,那么我想保持它的大小。 (我正在使用ASP.NET / C#)

如果您不想先通过加载来检查图像的属性,可以使用javascript进行操作:

  

而不是试图检查尺寸(这将是一种浪费,因为你几乎总是必须下载整个图像并处理它),为什么不将图像放在

元素中并设置max-height和容器的max-width样式到您想要的尺寸?

另一种选择是在您意识到图像时获取图像一次,将其resize以适当放入容器中,将其存储在服务器上并提供服务。

如果您知道它是JPEG,您只需拉出前几个字节并从图像标题中解析宽度/高度。

其他图像格式可能更难处理。 我认为,因为PNG会以块的forms完成所有事情,所以你不能只进行这种标题检查。

http://www.brettb.com/ASPNETUploadImageSize.asp

代码示例来自上述站点。 这是针对上传的图像,但它向您展示了如何从文件流中获取信息:

 private void ButtonUpload_Click(object sender, System.EventArgs e) { //Determine type and filename of uploaded image string UploadedImageType = UploadedPicture.PostedFile.ContentType.ToString().ToLower(); string UploadedImageFileName = UploadedPicture.PostedFile.FileName; //Create an image object from the uploaded file System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(UploadedPicture.PostedFile.InputStream); //Determine width and height of uploaded image float UploadedImageWidth = UploadedImage.PhysicalDimension.Width; float UploadedImageHeight = UploadedImage.PhysicalDimension.Height; //Check that image does not exceed maximum dimension settings if (UploadedImageWidth > 600 || UploadedImageHeight > 400) { Response.Write("This image is too big - please resize it!"); } }