给定图像的URL(而不是图像本身),获得它的尺寸最有效的是什么?我想更改图像标记(<img>
)中的高度和宽度属性,如果它大于200x200。但是,如果它小于那个,那么我想保持它的大小。 (我正在使用ASP.NET / C#)
答案 0 :(得分:4)
不是试图检查尺寸(这将是一种浪费,因为您几乎总是必须下载整个图像并对其进行处理),为什么不将图像放在<div>
元素中并设置容器的max-height
和max-width
样式是否为您想要的尺寸?
另一种选择是在您意识到这一点后获取图像,调整图像大小以适当放入容器中,将其存储在服务器上,并提供服务。
答案 1 :(得分:1)
如果您知道它是JPEG,您只需拉出first few bytes并从图像标题中解析宽度/高度。
其他图像格式可能更难处理。我认为既然PNG会以块的形式完成所有事情,你就不能只进行这种标题检查。
答案 2 :(得分:1)
如果您不想先通过加载来检查图像的属性,可以使用javascript执行此操作:
<img src="image.jpg" onload="if( this.width > 200 ) this.width = 200;">
答案 3 :(得分:0)
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!");
}
}