给定一个图片的URL(而不是图片本身),最有效的获取其尺寸的方法是什么?如果它的尺寸大于200x200,我想改变图像标签(<img>
)中的高度和宽度属性。但是,如果它小于这个尺寸,那么我希望保持原来的大小。(我正在使用ASP.NET/C#)
给定一个图片的URL(而不是图片本身),最有效的获取其尺寸的方法是什么?如果它的尺寸大于200x200,我想改变图像标签(<img>
)中的高度和宽度属性。但是,如果它小于这个尺寸,那么我希望保持原来的大小。(我正在使用ASP.NET/C#)
<div>
元素中,并将容器的 max-height
和 max-width
样式设置为所需的尺寸呢?如果您不想先加载图像来检查其属性,可以使用JavaScript进行操作:
<img src="image.jpg" onload="if( this.width > 200 ) this.width = 200;">
如果你知道这是一个JPEG格式的图片,你可以直接提取前几个字节并从图像头中解析出宽度/高度。
其他图像格式可能更难处理。我认为由于PNG格式将所有内容都分块处理,所以无法进行此类头部检查。
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!");
}
}