【发布时间】:2012-06-13 07:04:32
【问题描述】:
我正在尝试获取 asp:Image 的宽度(以像素为单位)。图片不是本地的。
imgUserThumb.Width.Value
总是以 0.0 的形式返回,有人知道为什么吗?或者也许那不是正确的方法? 此外,图像使用“onerror”属性来检查传递给它的图像 URL 是否有效,如果不是,则显示默认缩略图。
【问题讨论】:
我正在尝试获取 asp:Image 的宽度(以像素为单位)。图片不是本地的。
imgUserThumb.Width.Value
总是以 0.0 的形式返回,有人知道为什么吗?或者也许那不是正确的方法? 此外,图像使用“onerror”属性来检查传递给它的图像 URL 是否有效,如果不是,则显示默认缩略图。
【问题讨论】:
如果你没有设置图片标签的宽高,你会得到0。
如果您需要获取图像的实际大小,请将其加载到位图并从那里获取宽度。
Image img = new Bitmap("Mytest.png");
var imgwidth = img.Width;
private int GetImageWidth(string url)
{
int width = 0;
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential("name", "pw");
byte[] imageBytes = client.DownloadData(url);
using (MemoryStream stream = new MemoryStream(imageBytes))
{
var img = Image.FromStream(stream);
width= img.Width;
}
}
return width;
}
【讨论】: