dmx
dmx

Reputation: 1990

html avoid small images

I my application, I am displaying random images sent by backend (I receive them as link to images: ex : "http://example.com/image.png"), and I just use $('#theDiv').prepend('<img id="theImg" src=' + link + '/>') to append the image in my div. My problem is that sometimes, images are too small (for example less than 100k). I want to know if it is possible to detect very small images and don't add them to div ? If not, how can I implement my application to solve this ?

Thanks.

Upvotes: 1

Views: 56

Answers (2)

Jordi Flores
Jordi Flores

Reputation: 2150

Option 1: Your backend can give you image size in kb? You could add some filter.

Option 2: preload image in a hidden div, and check it's size before append it to it's target div.

Option 1 performance is better

Option 2 example:

$(function(){
  //on document ready check images sizes
  var minW = 1000;
  var minH = 300;
  $('.preload-wrapper img').each(function(index, item) {
    var thisW = $(item).width();
    var thisH = $(item).height();
    
    if (thisW >= minH && thisH >= minH) {
      //add to images wrapper
      $('.images-wrapper').append(item)
    }
        
    
    
    
  })
})
.preload-wrapper {
  position: absolute;
  left: 800000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

<div class="preload-wrapper">
  <img src="http://www.toolkit2collaborate.ca/wp/wp-content/uploads/2014/02/ICON_Example.png">
  <img src="https://cdn0.iconfinder.com/data/icons/customicondesignoffice5/256/examples.png">
  <img src="http://previews.123rf.com/images/carmenbobo/carmenbobo1412/carmenbobo141200628/34665210-Rubber-stamp-with-word-example-inside-vector-illustration-Stock-Vector.jpg"></div>

<div class="images-wrapper">
  
</div>

Upvotes: 1

Rax Shah
Rax Shah

Reputation: 531

-You can check image size in KB for this code and detect small images.
-If u want to get image size in bytes then remove '/1000'.

var obj = new XMLHttpRequest();
    obj.open('HEAD', 'natural.jpeg', true);
    obj.onreadystatechange = function(){
      if ( obj.readyState == 4 ) {
        if ( obj.status == 200 ) {
          if(obj.getResponseHeader('Content-Length')/1000 > 100)
          {
            alert('Valid image');
          }
          else
          {
            alert('Small image size '); 
          }
        } else {
          alert('ERROR');
        }
      }
    };
    obj.send(null); 

Upvotes: 2

Related Questions