我正在使用JavaScript,尝试从输入中获取文件并将其数据URI转换为ImageData值。这在从某个位置加载文件的桌面上正常工作。在iOS上,设备的相机打开,用户可以在其中拍照。加载图像后,可以正确读取数据URI,但由于网页崩溃而无法检索ImageData。
代码如下:
function handleChange() {
var fileInput = document.querySelector('input[type=file]');
var file = fileInput.files[0];
var reader = new FileReader();
reader.addEventListener("load", function() {
console.log(reader.result); // Logs on iOS
convertURIToImageData(reader.result).then(function(imageData) {
console.log(imageData); // Does not log on iOS
});
});
}
function convertURIToImageData(URI) {
return new Promise(function(resolve, reject) {
if (URI == null) return reject();
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var image = new Image();
image.addEventListener('load', function() {
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
console.log("drawn"); // Logs on iOS
resolve(context.getImageData(0, 0, canvas.width, canvas.height));
});
image.src = URI;
});
}
<input type="file" accept="image/*" capture="camera" onchange="handleChange()">
为什么在iOS上失败?