如何将选定的文件输入图像转换为 blob

fed*_*3vt 2 javascript

我想使用文件输入来选择一些图像。在我的 HTML 代码中,我有这个

<input type="file" ref="file" name="images[]">
Run Code Online (Sandbox Code Playgroud)

选择后,我想将每个选定的图像转换为一个斑点。我如何在我的 Vue 应用程序中实现这一目标?我不确定是否需要使用文件读取器,或者是否需要模拟 ajax 调用以将图像转换为 blob

Jac*_* Yu 9

您可以使用FileRead读取文件数据
,然后使用BlobURL.createObjectURL创建 blob url。

const fr = new FileReader()
const file = document.querySelector("input[name='images[]']").files[0]
fr.readAsArrayBuffer(file)
fr.onload = function() {
    // you can keep blob or save blob to another position
    const blob = new Blob([fr.result])

    // url for download
    const url = URL.createObjectURL(blob, {type: "image/png"});
    const a = document.createElement("a")
    a.href = url 
    a.download = "image"
    a.click()
}
Run Code Online (Sandbox Code Playgroud)