javascript - 使 HTML5 FileReader 处理 heic 文件
问题描述
当通过 FileReader api 从输入元素读取文件时,它可以工作,但我的 android 设备也允许发送文件,而且它似乎无论如何都发送 heic 文件,这会导致控制台中没有任何错误的空图像。直接从相机获取图像时,方向也是错误的。我刚刚找到要实现的重型库,我正在寻找更智能的解决方案。
JavaScript
function previewFile( e ) {
var preview = document.getElementById('usersProfilePicture');
var file = e.files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
HTML5
<form>
<label>
<input id="uploadProfilePicture" name=file type=file accept="image/jpg, image/jpeg, image/png, image/gif, image/bmp">
</label>
</form>
根本没有错误消息。无论我设置什么接受属性,桌面和安卓上的 Firefox、Chrome 都允许 .heic 文件。
最坏的解决方案:拒绝接受 .heic 文件 最佳解决方案:让 fileReader 处理 .heic 文件。在解决方案之间:检测 heic 并将其转换为 jpeg,客户端。
解决方案
通过使用库 heic2any,我现在有一个解决此问题的方法
(https://github.com/alexcorvi/heic2any)
检查输入的文件是否为 .heic,然后像这样使用库:
heic2any({
// required: the HEIF blob file
blob: file,
// (optional) MIME type of the target file
// it can be "image/jpeg", "image/png" or "image/gif"
// defaults to "image/png"
toType: "image/jpeg",
// conversion quality
// a number ranging from 0 to 1
quality: 0.5
})
我将此调用包装在一个承诺中,然后将结果传递给文件阅读器:
// uploadHEIC is a wrapper for heic2any
uploadHEIC(heicFile).then(function (heicToJpgResult) {
var reader = new Filereader();
reader.onload = function () {
// Do what you want to file
}
reader.readAsArrayBuffer(heicToJpgResult);
}
推荐阅读
- python - 更改 Dash 应用中按钮的 n_click 值
- node.js - 未定义:1 语法错误:位置 0 的 json 中的意外标记 <
- javascript - 使用拼接方法将多个元素插入数组
- oracle - 创建邮件通知请求链接功能
- java - 如何解决 Activity(用于回调绑定)?
- ruby-on-rails - postgres 在 2 db 列之间找到 IP 地址
- python - 有没有办法自动匹配多个参数相同?
- documentation - 我总是希望文档页面显示有关 API 参数输入的信息,但它从来没有。我该怎么做才能发现这一点?
- dropzone.js - 如何在 Dropzone 中提交预加载图像
- windows - 在不轮询的情况下检测 Windows 中的用户活动