2012-02-09 126 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

相关问题