我正在转换一个跨站点请求的实现,将图像从画布转换为基础64,然后转换为XMLHttpRequest和FileReader,这样就可以在web工作人员的内部使用。我想知道是否有一种方法可以得到图像的宽度和高度。
新函数
var convertFileToDataURLviaFileReader = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
// Our workaround for the Amazon CORS issue
// Replace HTTPs URL with HTTP
xhr.open('GET', url.replace(/^https:\/\//i, 'http://'));
xhr.send();
}我们的旧函数
var convertImgToDataURLviaCanvas = function(url, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
var allInfo = {
data: dataURL,
width: this.width,
height: this.height
}
// Add height and width to callback
callback(allInfo);
canvas = null;
};
// Our workaround for the Amazon CORS issue
// Replace HTTPs URL with HTTP
img.src = url.replace(/^https:\/\//i, 'http://');
}在旧的函数中,我可以使用画布获得高度和宽度,并在var allInfo中这样做。是否有一个等价的FileReader或某种方式来获得宽度和高度内的新功能?
为了澄清,我切换到XMLHttpRequest,因为Workers无法访问DOM,因此不能使用画布。
发布于 2016-02-01 19:15:25
看一下这段代码,它只是对这个示例https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL的快速重做
您的reader.result是64基编码的字符串吗?
<form>
<input type="file" onchange="previewFile()"><br>
<img src="" alt="Image preview..."><!-- height and width are not set -->
</form>
<script>
var previewFile = () => {
"use strict";
let file = document.querySelector("input[type=file]").files[0];
let fileReader = new FileReader();
let preview = document.querySelector("img")
fileReader.addEventListener("load", () => {
preview.src = fileReader.result;
// here preview.height and preview.width are accessible
// if height and width are not set in the img element in the html
});
if (file) {
fileReader.readAsDataURL(file);
}
};
</script>https://stackoverflow.com/questions/35137464
复制相似问题