HTML

HTML – Download image through AJAX and display it


AJAX was initially designed to be used with text data (JSON/HTML/XML) and that is why this requirement of downloading images using AJAX were never fulfilled.

But with HTML5, XHR2 has been introduced which allows us to get ArrayBuffer in ajax response and this is something which can be used to download image.

There are two approaches that could be taken.

  1. Download the image, create a blob object and use it as src in img.
  2. Download the image, and create data url and use it as src in img.


  
  
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState==4 && xhr.status==200) {
        var blob = new Blob([xhr.response], {
            type: xhr.getResponseHeader("Content-Type")
        });
        var imgUrl = window.URL.createObjectURL(blob);
        document.getElementById("img").src = imgUrl;
      }
    }
  xhr.responseType = "arraybuffer";
  xhr.open("GET","Hacker.jpg",true);
  xhr.send();
  




  
  
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState==4 && xhr.status==200) {
        document.getElementById("img").src = "data:"+xhr.getResponseHeader("Content-Type")+";base64," + btoa(String.fromCharCode.apply(null, new Uint8Array(xhr.response)));
      }
    }
  xhr.responseType = "arraybuffer";
  xhr.open("GET","Hacker.jpg",true);
  xhr.send();
  


Know more about XHR2 look at http://www.html5rocks.com/en/tutorials/file/xhr2/

HTML, jQUERY find actual size of image in img tag


Basically using DOM functions, if we try and get the size of <img />, we always get the dimensions of DOM element, not the actual image.

To be able to get actual size of image, we will have to reload it in a new <img /> without any size restriction. If we do that, this new <img /> will take dimensions of actual image, and using simple DOM methods we can get the actual size of image.

Sample HTML

<img src="http://doc.jsfiddle.net/_downloads/jsfiddle-desktop-1440x900-a.png" width="480" height="300">

JS trick

function getImageSize(url, callback){
    $('<img />').attr('src', url).load(function(){
        callback(this.width, this.height);
    });
}
getImageSize($("img").attr('src'), function(width, height){
        console.log(width, height);
});

Try this on JSFIDDLE.

HTML5 Update

HTML5 has introduced a much easier way of doing the same thing. If your browser supports HTML5, ignore the previous method and use this one.

$("img")[0].naturalWidth
$("img")[0].naturalHeight