2013-02-15 87 views
1

的高度和宽度,我必须为服务器端图像控制:如何计算图像

<img id="img" runat="server" style="padding-left:20px" 
     src="~/Images/2013-02-14_225913.png" /> 

我要计算其高度和宽度。我这样做:

int iWidth = (int)Math.Round((decimal)img.Width.Value); 
int iHeight = (int)Math.Round((decimal)img.Height.Value); 

这将返回-0,而不是实际参数。

如何获得图像控制的H & W?

+0

如果你的'img'是'Image'类的,只是'img.Height'应该给你的像素高度整数。 – 2013-02-15 09:26:31

+0

你想获得控件的大小或图片的真实大小吗? – 2013-02-15 09:40:41

+0

作为一个说法,'img'对象不具有'.Value'属性,因为它在服务器端被实例化为'System.Web.UI.HtmlControls.HtmlImage'。如果您使用'',那么该类将具有'System.Web.UI.WebControls.Image',它具有'.Value'属性。 – 2013-02-15 09:48:01

回答

1
Bitmap btmp; 
string image = "~/Images/2013-02-14_225913.png"; 
myBitmap = new Bitmap(image); 

int height= btmp.Height; 
int weight = btmp.Width; 
+0

谢谢。有效。但问题是图像路径来自另一个网站,而不是来自应用程序。说路径是:http://xyz/subsite/folder/img1.jpg所以当我们走这条路,它会抛出错误。我们如何使用此路径创建位图对象/ image – 2013-02-16 17:00:20

0

你的问题不是很清楚,所以有两种情况:

  1. 如果你指的是该控件的属性,那么你只能得到大小,如果你确实指定控件的属性在.aspx/.ascx文件中。

    有两个独立的类被使用:

    <img id="img1" runat="server" 
        style="padding-left: 20px" 
        src="meSepiaLarge.jpg" 
        width="100" height="100" /> 
    <asp:Image ID="img2" runat="server" 
        ImageUrl="~/meSepiaLarge.jpg" 
        Width="100px" Height="100px" /> 
    

    img1将被实例化作为在服务器侧的System.Web.UI.HtmlControls.HtmlImage,而img2将是一个System.Web.UI.WebControls.Image。以下是如何获得它们的尺寸。

    int i1Width = (int)Math.Round((decimal)img1.Width); 
    int i1Height = (int)Math.Round((decimal)img1.Height); 
    
    int i2Width = (int)Math.Round((decimal)img2.Width.Value); 
    int i2Height = (int)Math.Round((decimal)img2.Height.Value); 
    
  2. 如果你指的是与源图像的大小,那么你可以看看kad1r's answer

+0

谢谢。 Kad1r的答案奏效了。但问题是图像路径来自另一个网站,而不是来自应用程序。说路径是:xyz/subsite/folder/img1.jpg所以当我们走这条路时,它会抛出错误。我们如何使用这个路径创建位图对象/ image – 2013-02-16 17:46:53

0

你必须将其加载到内存&计算高度&宽度

 Bitmap myBitmap = new Bitmap(Server.MapPath("~/images/lightbulb.png")); 
     if (myBitmap != null) 
     { 
      Response.Write("Height:"+ myBitmap.Height + " & width:"+ myBitmap.Width); 
     } 
+0

谢谢!它通过位图工作。 – 2013-02-15 11:19:46

+0

谢谢。有效。但问题是图像路径来自另一个网站,而不是来自应用程序。说路径是:http://xyz/subsite/folder/img1.jpg所以当我们走这条路,它会抛出错误。我们如何使用这个路径/图像创建位图对象 – 2013-02-16 17:00:42