Search code examples
javascriptlocal-storageanimated-gif

Store animated GIF image in local Storage using pure JavaScript


I have a requirement where I need to store the GIF image in local storage. I have been trying to do this using following code:

function imgToURI(image) {
    var canvasTemp = document.createElement('canvas');
    canvasTemp.width = image.naturalWidth; // or 'width' if you want a special/scaled size
    canvasTemp.height = image.naturalHeight; // or 'height' if you want a special/scaled size
    canvasTemp.getContext('2d').drawImage(image, 0, 0);
    var dataUri = canvasTemp.toDataURL('image/gif');
    // Modify Data URI beginning
    dataUri = 'data:image/gif;' + dataUri.substring(15);
    return dataUri;
}


window.onload = function () {
    var img = new Image();
    img.src = 'http://pop.h-cdn.co/assets/16/33/480x264/gallery-1471381857-gif-season-2.gif';
    localStorage.setItem('test', imgToURI(img));
};

The above code outputs data:image/gif; in local storage. Also I can't find any errors on console.

I have been trying a lot but don't know why image is not getting stored. Please let me know if you have solution to above problem.


Solution

  • maybe when your code is executed the image was not loaded yet. So only the string 'data:image/gif will be saved

    var img = new Image();  
        img.addEventListener('load', function() {
          localStorage.setItem('test', imgToURI(img));
        }, false);
        img.src = 'http://pop.h-cdn.co/assets/16/33/480x264/gallery-1471381857-gif-season-2.gif';
    

    this code will attempt to save the image only if its loaded completely

    EDIT

    You are having this error because the image the image is not coming from your server: this CORS issue. you can try this but you have to trust the server who host the image

    just before the addEventListener

    img.setAttribute('crossOrigin', 'anonymous');