我实际上想知道为什么这样做的唯一方法是从文件中获取二进制数据,对其进行base64编码,然后将这个编码的字符串输入到Tag / HtmlImageElement中
纯 HTML
<img src="data:image/jpeg;base64,xxxxxxxxxxxxx...">
或通过javascript
let reader = new FileReader();
reader.readAsDataURL( droppedFile ); // this converts the binary data from the file into base64
reader.onloadend = () => {
const img = new Image();
img.src = reader.result;
img.onloadend = () => {
console.log(`image ${droppedFile.name} loaded.`);
}
}
一个奇怪的性能:数据是base64编码的,它将1MB图像转换为1.33MB字符串(这确实需要时间),然后放置在图像元素内,只是为了再次解码(这又需要时间)才能显示.. .
这是为什么?
真的没有办法用TypedArray(UInt8Arrays)来代替吗?
浏览器到底在哪里检查文件类型并检索放置的 jpg 文件的宽度和高度?
我知道另一种可能更快的方法。您直接获取 File 并将其转换为 ObjectURL。
这样:
const input = document.querySelector("input"),
img = document.querySelector("img")
input.addEventListener("change", () => {
if (input.files.length) {
const file = input.files[0],
url = (window.URL || window.webkitURL).createObjectURL(file)
img.src = url
} else {
img.src = ""
}
})
<input type="file" />
<img src="" />