The easiest way to do this is with the html helper. Please remember the additional success of checking the file system, even showing the image file name. The hit is small, but you will not notice any problems if you have too high traffic. Then you can implement some kind of caching so that the application βknowsβ if the file exists or not.
You can use a special helper for it
public static class ImageHtmlHelpers { public static string ImageUrlFor(this HtmlHelper helper, string contentUrl) {
Then, in your opinion, you can simply use the URL:
<img src="<% Html.ImageUrlFor("~/content/images/myfolder/myimage.jpg"); %>" />
EDIT: As Jim noted, I really did not address the issue of sizes. Personally, I use automatic size / size request management, which is a completely different story, but if you are concerned about the folder / sizes, just pass this information on to build the path. As below:
public static class ImageHtmlHelpers { public static string ImageUrlFor(this HtmlHelper helper, string imageFilename, ImageSizeFolderEnum imageSizeFolder) { UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext); string contentUrl = String.Format("~/content/userimages/{0}/{1}", imageSizeFolder, imageFilename); if (!File.Exists(helper.ViewContext.HttpContext.Server.MapPath(contentUrl))) { return urlHelper.Content(String.Format("~/content/userimages/{0}/none.png", imageSizeFolder)); } else { return urlHelper.Content(contentUrl); } } }
Then, in your opinion, you can simply use the URL:
<img src="<% Html.ImageUrlFor("myimage.jpg", ImageSizeFolderEnum.Small); %>" />
Enum was suggested for better program management if the folder is a fixed set, but for a quick and nasty approach, and not for the reason why you can't just use a line if the folder is generated by db, etc.