简体   繁体   English

在代码隐藏中设置图像宽度/高度-ASP.NET,C#

[英]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. 计划是根据宽度/高度来做比这更复杂的事情,因此不能将aspx文件中的宽度和高度设置为50%。

For some reason I always get 0 for width and height. 由于某种原因,我的宽度和高度总是为0。 Image1.ImageUrl is what i would expect though . Image1.ImageUrl是我所期望的 Any ideas? 有任何想法吗? Image is the System.Web.UI.Webcontrols.Image, not a System.Drawing.Image. 图像是System.Web.UI.Webcontrols.Image,而不是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. 要执行您想要的操作,我相信您将需要获取图像源并将其使用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. 然后,您就可以对高度和宽度进行调整,并将其应用于image标签的属性。

Remember with an img tag, you don't set width and height by default. 请记住,使用img标签时,默认情况下不会设置widthheight In this case, unless you set Width and Height , they will be 0 (or undefined). 在这种情况下,除非您设置WidthHeight ,否则它们将为0(或未定义)。 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. 取决于文件类型,.NET可能已经具有解码器或已将其加载的功能。 Load it into a Bitmap then query the width and height there. 将其加载Bitmap然后查询那里的宽度和高度。

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. 我不确定c#,但可以在VB.net中以这种方式进行编码,因此我确定有些东西是相当令人困惑的,并且它看起来可以解决您的意图,即使不是您的实际编码问题。

With dImage 使用dImage
.Width = 50% 宽度= 50%
.Height = 50% 高度= 50%
End With 结束于

I tried it both with setting the image height in my xaml as well as leaving it out. 我尝试了在我的xaml中设置图像高度以及将其遗漏的方法。

--edited for layout purposes. -出于布局目的进行了编辑。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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