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
function toDataURL(src, callback) {
var image = new Image();
image.crossOrigin = 'Anonymous'; image.onload = function() {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
context.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL('image/jpeg');
callback(dataURL);
}; image.src = src;
}

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
function toDataURL(src, callback) {
var xhttp = new XMLHttpRequest(); xhttp.onload = function() {
var fileReader = new FileReader();
fileReader.onloadend = function() {
callback(fileReader.result);
}
fileReader.readAsDataURL(xhttp.response);
}; xhttp.responseType = 'blob';
xhttp.open('GET', src, true);
xhttp.send();
}

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:

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

网络文件:

<!DOCTYPE html>
<html>
<head>
<title>Blob To Base64</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
</head>
<body>
<img id="showImg" />
<input type="button" value="Test" onclick="TestBase64();" />
</body>
</html>
<script type="text/javascript"> function TestBase64()
{
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"
toDataURL(fileUrl, function(base64)
{
document.getElementById('showImg').src = base64;
});
} function toDataURL(src, callback) {
var xhttp = new XMLHttpRequest(); xhttp.onload = function() {
var fileReader = new FileReader();
fileReader.onloadend = function() {
callback(fileReader.result);
}
fileReader.readAsDataURL(xhttp.response);
}; xhttp.responseType = 'blob';
xhttp.open('GET', src, true);
xhttp.send();
} </script>

  

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

  

 

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. laravel 中间件

    创建中间件命令 php artisan make:middleware CheckLogin 执行完以上命令会在app/Http/Middleware目录下创建一个新的中间件类CheckLogin.p ...

  2. jquery----扩展事件

    常用事件 blur([[data],fn]) 失去焦点 focus([[data],fn]) 获取焦点( 搜索框例子) change([[data],fn]) 当select下拉框中的元素发生改变的时 ...

  3. python接口自动化测试十六:unittest完成用例

    import unittestimport requests def add(a, b): print('前置条件!!!!!:如登录') return a + b class TestAAA(unit ...

  4. python3 读取文件跳过文件第一行内容

    Python编程时,经常需要跳过第一行读取文件内容.比较容易想到是为每行设置一个line_num,然后判断line_num是否为1,如果不等于1,则进行读取操作.相应的Python代码如下: #inp ...

  5. Ext.js入门:面板(五)

    一:Ext.Panel类简介 二:Ext.Panel类常用属性方法与事件 三:Ext.Panel实例运用 1.Ext.Panel类简介   类 Ext.Panel   包: Ext   定义的文件: ...

  6. SpringBank 开发日志 重新设计Action调用Service的参数传递 使用泛型解决类型转换问题

    之前想的比较简单,请求到达controller的时候,传给action的参数没有经过任何封装,就是一个Map.然后action再调用service的时候,传递的参数也是map @Controller ...

  7. 多线程中实现ApplicationContextAware接口获取需要的bean,applicationContext.getBea未返回也未报错

    唉,面试失败了有点难过. https://q.cnblogs.com/q/95168/#a_208239

  8. 解决Delphi7的自带的UTF-8编码转换函数BUG

    Delphi7及其以下版本的 VCL 只支持 Ansi, 所以... WideString 与 UTF8String (定义与 AnsiString 相同) 并没有办法正确的在 VCL 中显示 Del ...

  9. POJ 1703 Find them, Catch them (并查集)

    题意:有N名来自两个帮派的坏蛋,已知一些坏蛋两两不属于同一帮派,求判断给定两个坏蛋是否属于同一帮派. 思路: 解法一: 编号划分 定义并查集为:并查集里的元素i-x表示i属于帮派x,同一个并查集的元素 ...

  10. #1 // BZOJ 4361 isn

    Description 给出一个长度为n的序列A(A1,A2...AN).如果序列A不是非降的,你必须从中删去一个数, 这一操作,直到A非降为止.求有多少种不同的操作方案,答案模10^9+7.   题 ...