Search code examples
htmlasp.netimageoptimizationbandwidth

Asp.net: Variable image source for different screen resolution


Is there a way to select a different image source for different screen resolutions?

Like media queries but for only images

<img src="@<variable source for variable screen res.>@" />

to save some server bandwidth and to increase loading times for mobiles or small screens.

I have a 1800x900 image for HD screen and need to select a 900x300 version for another screen.

For those big background images within sliders, causing too much server load and time and money.


Solution

  • Using HTML:

    (Source: http://css-tricks.com/on-responsive-images/)

    <picture alt="description of image">
    
      <!-- low-res, default -->
      <source src="small.jpg">
    
      <!-- med-res -->
      <source src="medium.jpg" media="(min-width: 400px)">
    
      <!-- high-res -->
      <source src="large.jpg" media="(min-width: 800px)">
    
      <!-- Fallback content -->
      <img src="small.jpg" alt="description of image">
    
    </picture>
    

    This is a pretty new and experimental feature of HTML 5, see http://caniuse.com/#feat=picture

    Using JavaScript:

    There are couple of plugins that could solve the problem:

    Using CSS:

    With <div id="picture"></div> as a replacement to the IMG element:

    #picture {
         background-repeat: no-repeat;
         background-size: 100%;
    }
    
    @media (min-width: 800px) {
       #picture { background-image: url('small.jpg'); width: (SMALL_WIDTH); height: (SMALL_HEIGHT); }
    }
    
    @media (min-width: 1200px) {
       #picture { background-image: url('medium.jpg'); width: (MEDIUM_WIDTH); height: (MEDIUM_HEIGHT); }
    }
    
    @media (min-width: 1400px) {
       #picture { background-image: url('large.jpg'); width: (LARGE_WIDTH); height: (LARGE_HEIGHT); }
    }
    

    Using Server-Side Solutions: