我们可以使用canvas.toDataURL的方法将图片的绝对路径转换为base64编码;在这我们引用的是淘宝首页一张图片如下:
- var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";
代码如下:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
var dataURL = canvas.toDataURL("image/"+ext);
return dataURL;
}
var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";
var image = new Image();
image.src = img;
image.onload = function(){
var base64 = getBase64Image(image);
console.log(base64);
}
chrome 运行如下所示:
通过搜索明白,我们使用的是淘宝服务器上的一张图片,在本地服务器下访问,结果出现图片跨域的问题;为止,我们可以把图片放在本地服务器下即可解决上面的跨域问题;比如我现在将淘宝服务器下的图片保存在本地服务器下;如下代码即可解决:
var img = "http://127.0.0.1/base64/1.jpg";
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
var dataURL = canvas.toDataURL("image/"+ext);
return dataURL;
}
var image = new Image();
image.src = img;
image.onload = function(){
var base64 = getBase64Image(image);
console.log(base64);
}
但是有时候我们想引用其他服务器下的图片该如何解决呢?我们可以使用下面这一句代码在chrome和firefox下生效,在目前safari6以下貌似不支持;如下代码:
image.crossOrigin = '';
完整代码如下:
var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";
//var img = "http://127.0.0.1/base64/1.jpg";
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
var dataURL = canvas.toDataURL("image/"+ext);
return dataURL;
}
var image = new Image();
image.crossOrigin = '';
image.src = img;
image.onload = function(){
var base64 = getBase64Image(image);
console.log(base64);
}
如上代码在chrome和firefox下,经测试生效,在safari目前不支持;