开发者

Setting Image Width/Height in codebehind - ASP.NET, C#

开发者 https://www.devze.com 2023-01-09 06:44 出处:网络
I am trying to set the width and height of images in a datalist in the codebehind. The plan is to do something more complex than this based on the width/height, so setting width and height in the asp

I am trying to set the width and height of images in a datalist in the codebehind.

The plan is to do something more complex than this based on the width/height, so setting width and height in the aspx file to 50% is not an option.

For some reason I always get 0 for width and height. Image1.ImageUrl is what i would expect th开发者_StackOverflowough. Any ideas? Image is the System.Web.UI.Webcontrols.Image, not a System.Drawing.Image.

    protected void DataList9_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        Image Image1 = (Image)e.Item.FindControl("Image1");

        double height = Image1.Height.Value;
        double width = Image1.Width.Value;
        height = height * 0.5;
        width = width * 0.5;

        Image1.Height = new Unit(height);
        Image1.Width = new Unit(width);
    }


Your code above is referencing a image control that more then likely does not specify a width and or height.

To do what you want I believe you would need to get the source of the image and load it in memory using GDI. Then you could determine the width and height. Then you would be able to do your adjustments to the height and width and apply to the properties of the image tag.


Remember with an img tag, you don't set width and height by default. In this case, unless you set Width and Height, they will be 0 (or undefined). If you need the actual (image, pixels) width and height, you'll need to discover that for yourself by loading the image into memory.

Depending on the filetype, .NET probably has a decoder or the ability to load it already. Load it into a Bitmap then query the width and height there.


I am not sure about c# but I can code it this way in VB.net, so I am sure there is something equivelant and it looks like it will solve your intent if not your actual coding problem.

With dImage
   .Width = 50%
   .Height = 50%
End With

I tried it both with setting the image height in my xaml as well as leaving it out.

--edited for layout purposes.


Have you tried declaring/defining an OnLoad handler for the image and setting the height/width in there?

0

精彩评论

暂无评论...
验证码 换一张
取 消