Note that there are some explanatory texts on larger screens.

plurals
  1. POExtend Image server control to specify image dimensions automatically
    text
    copied!<p>The browser would render a webpage faster if it knows the images dimensions. But how can I assign the Width and Height in ASP.NET automatically?</p> <p>I can do a server control extending Image that would query the image size using GDI+ and assign those values to its own Width and Height properties.</p> <p>But there are several things that worries me and would like to hear opinions:</p> <ul> <li>Cache: What is the best way to implement cache? I would like to cache the Height and Width values across all pages for each image.</li> <li>Which method should I use to query the image size? The constructor or another method (OnInit, OnPreRender, etc, etc)?</li> <li>Is it GDI+ the best option to query image size, or is there any other efficient way?</li> <li>How can I query the size for remotes images?</li> </ul> <p>Of course I have an idea of how to do all that I mentioned, but I wanted to hear some thoughts.</p> <p><a href="http://code.google.com/speed/page-speed/docs/rendering.html#SpecifyImageDimensions" rel="nofollow">http://code.google.com/speed/page-speed/docs/rendering.html#SpecifyImageDimensions</a></p> <p>EDIT: This is what I have so far:</p> <pre><code>[ToolboxData("&lt;{0}:AutoSizeImage runat=server&gt;&lt;/{0}:AutoSizeImage&gt;")] public class AutoSizeImage : Image { protected override void OnPreRender(EventArgs e) { if (Width.Value + Height.Value == 0) { if (IsLocal(ImageUrl)) { using (System.Drawing.Image img = System.Drawing.Image.FromFile(Context.Server.MapPath(ImageUrl))) { Width = img.Width; Height = img.Height; } } else { System.Net.WebRequest request = System.Net.WebRequest.Create(ImageUrl); using (System.Net.WebResponse response = request.GetResponse()) using (System.IO.Stream responseStream = response.GetResponseStream()) using (System.Drawing.Image img = System.Drawing.Image.FromStream(responseStream)) { Width = img.Width; Height = img.Height; } } } base.OnPreRender(e); } private bool IsLocal(string p) { return !(p.StartsWith("http://") || p.StartsWith("https://") || p.StartsWith("ftp://")); } } </code></pre> <p>It works beautifully, but I need to implement cache now. I want to cache the output of this control for each value of ImageUrl, that is, I want the OnPreRender method to be called once for each image. Is that possible?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload