JavaScript – Convert Image to Base64 String
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
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
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的更多相关文章
- csharp:Convert Image to Base64 String and Base64 String to Image
/// <summary> /// 图像转成二进制数组 /// </summary> /// <param name="imageIn">< ...
- convert image to base64
ylbtech-Unitity-cs:convert image to base64 convert image to base64 1.A,效果图返回顶部 1.B,源代码返回顶部 1.B.1,c ...
- 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 如何在不将数字转换 ...
- convert image to base64 in javascript
convert image to base64 in javascript "use strict"; /** * * @author xgqfrms * @license MIT ...
- PIL.Image与Base64 String的互相转换
https://www.jianshu.com/p/2ff8e6f98257 PIL.Image与Base64 String的互相转换 mona_alwyn 2018.01.18 19:02* 字数 ...
- How to convert any valid date string to a DateTime.
DateTimeFormatInfo pattern = new DateTimeFormatInfo() { ShortDatePattern = "your date pattern&q ...
- javaScript 工作必知(三) String .的方法从何而来?
String 我们知道javascript 包括:number,string,boolean,null,undefined 基本类型和Object 类型. 在我的认知中,方法属性应该是对象才可以具有的 ...
- 异常-----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 ...
- Convert CString to ANSI string in UNICODE projects
Convert CString to ANSI string in UNICODE projects Quick Answer: use an intermediate CStringA. Norma ...
随机推荐
- PHP时间类完整实例
<?php header("Content-type:text/html;Charset=utf-8"); class time{ private $year;//年 pri ...
- js事件驱动函数
输入框 获得光标的这个行为叫做获取焦点 失去光标的这个行为叫做失去焦点 blur 失去焦点 1.获取标签的时候,一定要先等页面加载完成,再去获取这个标签. 可以将整个script代码写在body的下面 ...
- python 全栈开发,Day45(html介绍和head标签,body标签中相关标签)
一.html介绍 1.web标准 web准备介绍: w3c:万维网联盟组织,用来制定web标准的机构(组织) web标准:制作网页遵循的规范 web准备规范的分类:结构标准.表现标准.行为标准. 结构 ...
- jquery.Inputmask 插件用法(中文API文档)
jquery.Inputmask 可以算是input文本输入限制的神器了,内部融合了多种输入限制, 如金额,电话号码,身份证号,网关等..,并且还可以自定义规则. inputmask 据说最早起源 ...
- [ZJOI2010]贪吃的老鼠
很不错的一道网络流的题目 二分答案是显然的 首先不考虑每个饼干只能一个老鼠吃 那很显然的建图就是将时间点按照开始结束的点分成2*n-1段 然后对每一段时间建m个老鼠的点,然后s-它限流,再从它到目前可 ...
- 百度地图API如何给自定义覆盖物添加事件
摘要: 给marker.lable.circle等Overlay添加事件很简单,直接addEventListener即可.那么,自定义覆盖物的事件应该如何添加呢?我们一起来看一看~ --------- ...
- MT4编程初级手册
http://www.fxunion.com/college/2015/17554.html
- BZOJ1053 [HAOI2007]反素数ant 数论
欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 传送门 - BZOJ1053 题目描述 对于任何正整数x,其约数的个数记作g(x).例如g(1)=1.g(6)=4.如果某个正 ...
- java实体转json忽略属性
1: import com.alibaba.fastjson.annotation.JSONField; fastjson 过滤指定字段 @JSONField(serialize=false)priv ...
- 【Java并发核心五】Future 和 Callable
默认情况下,线程Thread对象不具有返回值的功能,如果在需要取得返回值的情况下会极为不方便.jdk1.5中可以使用Future 和 Callable 来获取线程返回值. Callable 可以 看成 ...