From: https://bytenota.com/javascript-convert-image-to-base64-string/

his post shows you two approaches how to convert an image to a Base64 string using JavaScript: HTML5 Canvas and FileReader.

1. Approach 1: HTML5 Canvas

example.js
  1. function toDataURL(src, callback) {
  2. var image = new Image();
  3. image.crossOrigin = 'Anonymous';
  4. image.onload = function() {
  5. var canvas = document.createElement('canvas');
  6. var context = canvas.getContext('2d');
  7. canvas.height = this.naturalHeight;
  8. canvas.width = this.naturalWidth;
  9. context.drawImage(this, 0, 0);
  10. var dataURL = canvas.toDataURL('image/jpeg');
  11. callback(dataURL);
  12. };
  13. image.src = src;
  14. }

The above code we load the image into Image object, draw it to the canvas and then convert it to Base64 image data URL.

2.  Approach 2: FileReader

example.js
  1. function toDataURL(src, callback) {
  2. var xhttp = new XMLHttpRequest();
  3. xhttp.onload = function() {
  4. var fileReader = new FileReader();
  5. fileReader.onloadend = function() {
  6. callback(fileReader.result);
  7. }
  8. fileReader.readAsDataURL(xhttp.response);
  9. };
  10. xhttp.responseType = 'blob';
  11. xhttp.open('GET', src, true);
  12. xhttp.send();
  13. }

The above code we load the image as Blob via XMLHttpRequest, then use FileReader to convert the image to Base64 image data URL.

Use the function:

  1. toDataURL('https://www.gravatar.com/avatar', function(dataURL) {
  2. // do something with dataURL
  3. console.log(dataURL);
  4. });
  5. 但是这两种都是需要图片服务器允许跨域资源访问才可以,对于第二种方法,如果图片服务器不允许跨域资源访问, XMLHttpRequestonload事件就不会执行.
  6. 注: 在实际的应用中,发现Canvas转换gif动图的时候只能取到第一帧,结果动图变成了静图,而FileReader方法则可以成功转换动图.下面两段代码分别用来出来本地文件和网络文件:
  7. 本地文件:
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Blob To Base64</title>
  5. <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  6. </head>
  7. <body>
  8. <img id="showImg" />
  9. <input type="file" onchange="changeFile(event);" />
  10. </body>
  11. </html>
  12. <script type="text/javascript">
  13. function changeFile(event) {
  14. file = event.target.files[0];
  15. var a = new FileReader();
  16. a.onload = function (e) {
  17. var base64Str = e.target.result;//获取base64
  18. //下面是测试得到的base64串能否正常使用:
  19. document.getElementById('showImg').src = base64Str;
  20. }
  21. a.readAsDataURL(file);
  22. }
  23. </script>

网络文件:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Blob To Base64</title>
  5. <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  6. </head>
  7. <body>
  8. <img id="showImg" />
  9. <input type="button" value="Test" onclick="TestBase64();" />
  10. </body>
  11. </html>
  12. <script type="text/javascript">
  13.  
  14. function TestBase64()
  15. {
  16. var fileUrl = "http://29e5534ea20a8.cdn.sohucs.com/c_zoom,h_86/c_cut,x_8,y_0,w_225,h_150/os/news/e4337401e7ebeac6f7cdb52fac9807e5.gif"
  17. toDataURL(fileUrl, function(base64)
  18. {
  19. document.getElementById('showImg').src = base64;
  20. });
  21. }
  22.  
  23. function toDataURL(src, callback) {
  24. var xhttp = new XMLHttpRequest();
  25.  
  26. xhttp.onload = function() {
  27. var fileReader = new FileReader();
  28. fileReader.onloadend = function() {
  29. callback(fileReader.result);
  30. }
  31. fileReader.readAsDataURL(xhttp.response);
  32. };
  33.  
  34. xhttp.responseType = 'blob';
  35. xhttp.open('GET', src, true);
  36. xhttp.send();
  37. }
  38.  
  39. </script>

  

另外找动图可以到这里面来找: https://tieba.baidu.com/p/4674320064

  

  1.  

JavaScript – Convert Image to Base64 String的更多相关文章

  1. csharp:Convert Image to Base64 String and Base64 String to Image

    /// <summary> /// 图像转成二进制数组 /// </summary> /// <param name="imageIn">< ...

  2. convert image to base64

    ylbtech-Unitity-cs:convert image to base64 convert image to base64 1.A,效果图返回顶部   1.B,源代码返回顶部 1.B.1,c ...

  3. how to convert a number to a number array in javascript without convert number to a string

    how to convert a number to a number array in javascript without convert number to a string 如何在不将数字转换 ...

  4. convert image to base64 in javascript

    convert image to base64 in javascript "use strict"; /** * * @author xgqfrms * @license MIT ...

  5. PIL.Image与Base64 String的互相转换

    https://www.jianshu.com/p/2ff8e6f98257 PIL.Image与Base64 String的互相转换 mona_alwyn 2018.01.18 19:02* 字数 ...

  6. How to convert any valid date string to a DateTime.

    DateTimeFormatInfo pattern = new DateTimeFormatInfo() { ShortDatePattern = "your date pattern&q ...

  7. javaScript 工作必知(三) String .的方法从何而来?

    String 我们知道javascript 包括:number,string,boolean,null,undefined 基本类型和Object 类型. 在我的认知中,方法属性应该是对象才可以具有的 ...

  8. 异常-----Can't convert the date to string, because it is not known which parts of the date variable are in use. Use ?date, ?time or ?datetime built-in, or ?string.\u003Cformat> or ?string(format) built-

    1.错误描述 五月 27, 2014 12:07:05 上午 freemarker.log.JDK14LoggerFactory$JDK14Logger error 严重: Template proc ...

  9. Convert CString to ANSI string in UNICODE projects

    Convert CString to ANSI string in UNICODE projects Quick Answer: use an intermediate CStringA. Norma ...

随机推荐

  1. C++ code:数值计算之矩形法求解积分问题

    积分的通常方法是将区域切割成一个个的小矩形,然后求这些小矩形的和.小矩形切割得越细,计算精度就越高,可以将切割小矩形的数量作为循环迭代变量,将前后两个不同精度下的小矩形和之差,作为逼近是否达到要求的比 ...

  2. MVC开发中的常见错误-07-“System.IO.DirectoryNotFoundException”类型的未经处理的异常在 mscorlib.dll 中发生

    “System.IO.DirectoryNotFoundException”类型的未经处理的异常在 mscorlib.dll 中发生 其他信息: 未能找到路径“F:\Users\home\Docume ...

  3. list的遍历

    package list; import java.util.ArrayList;import java.util.Iterator;import java.util.List; /* * list的 ...

  4. HDU1711 Number Sequence(KMP模板题)

    Number Sequence Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  5. MyBatis查询,返回值Map或List<Map>

    一.返回值Map 1.mapper.xml <select id="selectUserMapLimitOne" resultType="java.util.Has ...

  6. Java编程的逻辑 (12) - 函数调用的基本原理

    本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http:/ ...

  7. AngularJS+Node.js+socket.io 开发在线聊天室

    所有文章搬运自我的个人主页:sheilasun.me 不得不说,上手AngularJS比我想象得难多了,把官网提供的PhoneCat例子看完,又跑到慕课网把大漠穷秋的AngularJS实战系列看了一遍 ...

  8. 基于OSGI.NET的MVC插件式开发

    最近在研究OSGI.NET插件式开发框架.官方网站提供了一个基于OSGI.NET的插件仓库.下载官方的SDK包安装后VS项目模板会多出一组iOpenWorks项目模板.在学习过程中,发现通过iOpen ...

  9. python 字符串组成MySql 命令时,字符串含有单引号或者双引号导致出错解决办法

    引用自:https://blog.csdn.net/zhaoya_huangqing/article/details/48036839 一.在组成SQL语句并发送命令时完全按照Python中的样式去传 ...

  10. Scrapy爬虫学习笔记 - 爬虫基础知识

    一.正则表达式 二.深度和广度优先                                三.爬虫去重策略