2013-02-15 82 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