2012-02-09 131 views
0

我想要按比例更改我在asp.net中圖像的大小,問題是我無法獲取從數據庫加載的圖像的實際大小。這裏是代碼:如何獲取圖像控件的寬度和高度

imgAvatar.ImageUrl = "~/Modules/FileViewer.ashx?id=" + o.EventID;      
     double r = imgAvatar.Width.Value/300.00; 
     imgAvatar.Width = new Unit(300, UnitType.Pixel); 
     imgAvatar.Height = new Unit(imgAvatar.Height.Value/r, UnitType.Pixel); 

imgAvatar.Width.Value總是0.0。 你會對我建議什麼?

+0

你應該做的FileViewer.ashx調整,據我可以看到,處理程序提供圖像,那麼爲什麼不調整它的大小呢? – 2012-02-09 12:22:51

回答

1

請勿設置寬度和高度。呈現的IMG標記將根據下載圖像的大小進行調整。

但是,如果圖像太大,您可能會遇到問題。在這種情況下,使用CSS來設置最高:

max-width: 300px; 
max-height: 300px; 

我可能有誤解的問題,考慮到我上面的答案。不管怎麼說,我看到作到的都將與此類似的方式:

System.Drawing.Image image = System.Drawing.Image.FromFile(this.Server.MapUrl("~/image path here")); 

// sorry if the above line doesn't compile; writing from memory, use intellisense to find these classes/methods 

// image.Width and image.Height will work here 
+0

如果我設置最大寬度和最大高度是否會按比例限制尺寸?第二個選項是無效的,因爲我不能在MapUrl中僞裝我的圖像的URL,它會導致「Ilegal字符異常」,導致我的圖像url包含「?」 – Andron 2012-02-09 11:40:55

+0

#1是的,大小將成比例;它將小於或等於您設置的最大值。 #2,如果你想這樣做,從路徑中去除額外的字符:'int idx = pathString.IndexOf('?')',然後'if(idx> 0)pathString.Substring(0,idx)'; – 2012-02-09 11:47:50

0

採取與位圖圖像的大小,並調用下面的函數來這裏調整

Bitmap myBitmap; 
string fileName = "foreverAlone.jpg"; 
myBitmap = new Bitmap(fileName); 

Size newSize = NewImageSize(myBitmap.Height, myBitmap.Width, 100);//myBitMap.Height and myBitMap.Width is how you take the original size 

檢查Bitmap類Bitmap Class - MSDN Article

該代碼返回圖像的新大小,並且圖像質量保持不變--no reduce-,FormatSize參數決定新大小。

public Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize) 
     { 
      Size NewSize; 
      double tempval; 

      if (OriginalHeight > FormatSize && OriginalWidth > FormatSize) 
      { 
       if (OriginalHeight > OriginalWidth) 
        tempval = FormatSize/Convert.ToDouble(OriginalHeight); 
       else 
        tempval = FormatSize/Convert.ToDouble(OriginalWidth); 

       NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight)); 
      } 
      else 
       NewSize = new Size(OriginalWidth, OriginalHeight); 

      return NewSize; 
     } 
+0

其實這個問題究竟是怎樣才能得到原來的高度! – Andron 2012-02-09 11:46:33

+1

@Andron對不起,沒有必要喊出標點符號。在這裏我編輯我的帖子。 – Bastardo 2012-02-09 11:51:35

+0

@RoboLover不要冒犯我只是想強調一下。 – Andron 2012-02-09 11:56:08

相關問題