javascript从image转换为base64位编码的String

最近需要把app的微信分享方法开放给webview,涉及到分享的图片,如果通过传送图片连接,那将要在后台再取一次图片文件,会影响速度,我选择webview把image以base64位编码的方式传给本地应用。 下面是实现的参考代码:

<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Image to Base64 - jsFiddle demo by handtrix</title> <script type='text/javascript' src='https://code.jquery.com/jquery-2.0.2.js'></script> <link type="text/css" href="https://www.jb51.net/css/result-light.css" > <style type='text/css'> @import url('//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css'); body{ padding: 20px; } </style> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ /** * convertImgToBase64 * @param {String} url * @param {Function} callback * @param {String} [outputFormat='image/png'] * @author HaNdTriX * @example convertImgToBase64('http://goo.gl/AOxHAL', function(base64Img){ console.log('IMAGE:',base64Img); }) */ function convertImgToBase64(url, callback, outputFormat){ var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var img = new Image; img.crossOrigin = 'Anonymous'; img.onload = function(){ canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img,0,0); var dataURL = canvas.toDataURL(outputFormat || 'image/png'); callback.call(this, dataURL); // Clean up canvas = null; }; img.src = url; } $('#img2b64').submit(function(event){ var imageUrl = $(this).find('input[name=url]').val(); console.log('imageUrl', imageUrl); convertImgToBase64(imageUrl, function(base64Img){ $('.output') .find('textarea') .val(base64Img) .end() .find('a') .attr('href', base64Img) .text(base64Img) .end() .find('img') .attr('src', base64Img); }); event.preventDefault(); }); });//]]> </script> </head> <body> <h2>Input</h2> <form> <input type="url" placeholder="Insert an IMAGE-URL" value="http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png" required> <span> <input type="submit"> </span> </form> <hr> <h2>Output</h2> <div> <textarea></textarea><br> <a></a><br><br> <img><br> </div> </body> </html>

PS:这里再为大家提供一款在线图片转base64编码的工具供大家参考使用:

图片转换为Base64编码在线工具

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgpyxg.html