views:

841

answers:

2

I'm having trouble consistently setting the width and height of an img tag. The img src is pulled dynamically from a database. The images being pulled from the database can have varying widths and heights so I need to set the img control. Sometimes the width and height are set properly and sometimes they aren't. I can't figure out why. Any help would be greatly appreciated. Thanks!

Here is what I'm doing now.

try
    {
        byte[] byteArray = GetImage();
        using (Bitmap bmp = ByteArrayToBitmap(byteArray))
        {
            //image is the img tag.
            image.Style["width"] = bmp.Width.ToString();
            image.Style["height"] = bmp.Height.ToString();
        }
    }
    catch (Exception ex)
    { }

EDIT: This appears to be a problem only in IE. Chrome and Firefox seem to be working fine. Also, when IE7 doesn't display the image with the proper height/width if the browser is refreshed it then displays properly. Sometimes...

+2  A: 

This is because you need to remove the width and height attributes of the tag. Simply changing the CSS image width and height values will not work.

Try something like so, this is in Javascript;


imageTag.removeAttribute('width');
imageTag.removeAttribute('height');
Gary Green
Thanks for trying but it didn't work. I did as you said in codebehind in Page_PreInit().
SquidScareMe
Did you try doing it *everytime* a new image is loaded? Try debugging and work out exactly what the database is returning, and if there is any pattern to when it doesn't work.
Gary Green
+2  A: 

Looking at your code, I would suggest another approach; since you already have a copy of the image in your byte array, why not have your application resize the image and return a predictable size to the client? You would gain the benefit of not worrying about how different browsers resize and possibly reduce the quality of the image.

Example here... http://www.west-wind.com/Weblog/posts/283.aspx

routeNpingme
Good idea but the problem is the images have different height to width ratios. If I resize to a height and width I choose I run the risk of distorting the image. There is no universal size I can resize them to.
SquidScareMe
That's fine though - what you can do is define a maximum width OR height, and then calculate the maximum size that you can make it until it meets the height or width requirement. Then just find the % between the original and your end #, and size the other dimension down. Want a code sample?
routeNpingme
Ben Scheirman
IE7 can do anisotropic resizing if you tell it to: http://code.flickr.com/blog/2008/11/12/on-ui-quality-the-little-things-client-side-image-resizing/
Zhaph - Ben Duguid