简体   繁体   中英

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

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 though . 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.

您是否尝试过为图像声明/定义OnLoad处理程序并在其中设置高度/宽度?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM