最近在做项目的时候,想调用一个接口。接口中一个参数要求需要图片的base64字符串,所以下面整理了一下图片转base64字符串的方法:
方法1:(根据图片路径)
var image = new Image();
image.src = imgurl; //imgurl 就是你的图片路径
image.onload = function(){
var base64 = getBase64Image(image);
console.log(base64);
}
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;
}
方法2:(根据上传图片)
<input type="file" id="testFile" />

项目中遇到接口要求图片参数为base64字符串,本文介绍了两种方法:1.通过图片路径转换,2.处理上传图片转换。同时提醒注意:1.调用时可能需要去除base64头部信息,2.确保base64编码不超过4M,3.可获取图片尺寸信息。
最低0.47元/天 解锁文章
767

被折叠的 条评论
为什么被折叠?



