Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode Animated GIF to Base64

I've been searching for a way to encode animated GIF's from a given URL to base64 without using external libraries like jquery (I will use it if absolutely necessary). I have found results to encode static images to base64, but they all use the canvas, and canvas.toDataURL() will only encode a single frame of an animated GIF. Is there a way to encode animated GIF's (or any image for that matter) to base64 without using the canvas?

like image 690
jocopa3 Avatar asked Mar 02 '14 06:03

jocopa3


1 Answers

Yes, you can use FileReader.readAsDataURL() (example based on MDN web docs) :

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.addEventListener("load", function () {
    var base64gif = reader.result; // your gif in base64 here
    preview.src = base64gif;
    document.getElementById('base64').innerHTML = base64gif;
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}
Upload your gif:<br/>
<input type="file" onchange="previewFile()"><br/>
<div id="base64" style="max-width: 200px; float: left; overflow-wrap: break-word;"></div>
<img src="" height="200" alt="Gif preview...">
like image 105
falsarella Avatar answered Oct 22 '22 17:10

falsarella