首页 > 解决方案 > 使 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,客户端。

标签: javascripthtmlimagefilereaderheic

解决方案


通过使用库 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);
}

推荐阅读