Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to display default image if specified image file is not found?

I've got your average e-Commerce app, I store ITEM_IMAGE_NAME in the database, and sometimes managers MISSPELL the image name.

To avoid "missing images" (red X in IE), every time I display the list of products, I check the server for the image related to the product, and if that file doesn't exist - I replace it with default image.

As far as i can tell this doesn't affect performance, but I was wondering if there are any alternatives to fix a "missing image" problem.

I'm using ASP.NET + C# (.NET 3.5)

Some code:

foreach (Item item in Items)
{
  string path = Path.Combine("~/images/", item.categoryImage);
  item.categoryImage = File.Exists(Server.MapPath(path)) ? item.categoryImage : GetImageDependingOnItemType();
}
like image 558
roman m Avatar asked Apr 04 '09 20:04

roman m


2 Answers

You might consider something with javascript

<img src="image.jpg" onerror="this.onerror=null;this.src='default.jpg'">

Edit: Or program a 404.aspx returning a default image, if a nonexisting image was requested.

like image 144
Erik Avatar answered Oct 13 '22 02:10

Erik


<style>
  .fallback { background-image: url("fallback.png"); }
</style>

<img class="fallback" src="missing.png" width="400" height="300">

If missing.png loads, it will cover the space allocated for it, as if the fallback were not specified. (Assuming it's not transparent.)

If missing.png fails to load, the space will instead be filled with fallback.png. You'll still get a little "broken image" icon, but I prefer it that way... a little hint that says "fix me".

If your images aren't all the same size, you'll notice that the background tiles by default. You can use background-repeat: no-repeat; if you don't like that.

like image 42
ephemient Avatar answered Oct 13 '22 04:10

ephemient