使 HTML5 FileReader 处理 heic 文件

Sas*_*dau 5 html javascript image filereader heic

当 FileReader api 从 input 元素读取文件时,它可以工作,但我的 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 = "";
    }
}
Run Code Online (Sandbox Code Playgroud)

HTML5

<form>
    <label>
        <input id="uploadProfilePicture" name=file type=file accept="image/jpg, image/jpeg, image/png, image/gif, image/bmp">
    </label>
</form>
Run Code Online (Sandbox Code Playgroud)

根本没有错误消息。无论我设置什么接受属性,桌面和 Android 上的 Firefox、Chrome 都允许 .heic 文件。

最坏的解决方案:拒绝接受 .heic 文件 最佳解决方案:让 fileReader 使用 .heic 文件。中间解决方案:检测heic并将其转换为jpeg,客户端。

Jor*_*ger 12

上面的答案很好地解释了这一点,但对于任何寻找另一个示例的人,我稍微修改了 Heic2Any 的示例(https://alexcorvi.github.io/heic2any/

<input type="file" id="heic" onchange="convertHEIC(event)">
Run Code Online (Sandbox Code Playgroud)
async function convertHEIC (event){
    let output = document.getElementById('output');

    //if HEIC file
    if(event.target.files[0] && event.target.files[0].name.includes(".HEIC")){
        // get image as blob url
        let blobURL = URL.createObjectURL(event.target.files[0]);
        
        // convert "fetch" the new blob url
        let blobRes = await fetch(blobURL)

        // convert response to blob
        let blob = await blobRes.blob()

        // convert to PNG - response is blob
        let conversionResult = await heic2any({ blob })

        // convert to blob url
        var url = URL.createObjectURL(conversionResult);
        document.getElementById("target").innerHTML = `<a target="_blank" href="${url}"><img src="${url}"></a>`;
    
    }       
};
Run Code Online (Sandbox Code Playgroud)


小智 5

我现在通过使用库 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
    })
Run Code Online (Sandbox Code Playgroud)

我将此调用包装在一个承诺中,然后将结果传递给文件读取器:

// 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);
}
Run Code Online (Sandbox Code Playgroud)