简体   繁体   English

将动画GIF编码为Base64

[英]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). 我一直在寻找一种方法来将动画GIF从给定的URL编码到base64,而不使用像jquery这样的外部库(如果绝对必要,我将使用它)。 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. 找到了将静态图像编码为base64的结果,但它们都使用canvas ,而canvas.toDataURL()只编码动画GIF的单帧。 Is there a way to encode animated GIF's (or any image for that matter) to base64 without using the canvas ? 有没有办法在不使用canvas情况下将动画GIF(或任何图像)编码到base64?

Yes, you can use FileReader.readAsDataURL() (example based on MDN web docs) : 是的,您可以使用FileReader.readAsDataURL() (基于MDN Web文档的示例)

 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..."> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM