javascript - 从文件路径中检索图像并将其编码为 Base64
问题描述
我需要从提供的图像文件路径转换 Base64。以下是转换代码:
var encodeImageUri = function(imageUri, callback) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function() {
c.width = this.width;
c.height = this.height;
ctx.drawImage(img, 0, 0);
if(typeof callback === 'function'){
var dataURL = c.toDataURL("image/jpeg");
callback(dataURL);
}
};
img.src = imageUri;
}
function getFileContentAsBase64(path,callback){
console.log(path);
window.resolveLocalFileSystemURL(path, gotFile, fail);
function fail(e) {
alert(JSON.stringify(e));
}
function gotFile(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var content = this.result;
callback(content);
};
// The most important point, use the readAsDatURL Method from the file plugin
reader.readAsDataURL(file);
});
}
}
我如何使用它:
var image = 'file://' + path;
getFileContentAsBase64(image, function (base64File) {});
encodeImageUri(image, function(base64){});
path
例子:
文件:///storage/emulated/0/test.jpeg
如果我将 base64 结果打印到Code Beautifier,则一个已损坏,仅 3kb 大小,而另一个 1 是带有损坏图像图标的错误。
解决方案
推荐阅读
- html - 默认情况下,本地主机添加到 reactjs 中 href 提供的 url
- vue.js - Vue.js 从多个数组添加对象
- html - 我们可以用 display: table 为 div 设置一个固定的高度吗?
- .net - dotnet 工具列表未显示任何已安装的工具且无法更新它们
- javascript - 如何对数组键值进行分组
- python - 我收到使用 Pandas 数据框在 Python 上使用 GeoJson 创建 Choropleth 地图的错误消息
- javascript - 地图的缩放滑块非常小
- python - 将字典合并到列表问题中 - python
- vector - rust Vector中是否有类似“Array.prototype.some”的方法?
- angular - Angular - 使用 fs 读取 app 目录中的二进制图像文件?