作为文件上传器的一部分,我有一些图像预览功能,可以在上传之前显示图像。在此过程中,图像预览使用
htmlImageElement.decode()
方法,该方法返回一个promise,以便在图像上进行各种前端验证等。这
decode()
方法在中调用的函数内运行
forEach()
与文件中的文件相关的循环
<input>
要素
上下文
尽管我将每次上传的文件数量限制为10个,因为允许大文件,但如果用户附加了10个(大)文件,则无论是在图像渲染方面,还是在从预览器中删除任何图像时,图像预览器都会滞后。
问题
是否有办法在不影响要上传的图像的文件大小的情况下缩小图像预览的文件大小?
可以将宽度和高度参数添加到
new Image()
构造函数,即。
new Image(300,300)
,但这些只会影响显示大小,而不会影响文件大小,并且如果您更改
naturalHeight
和
naturalWidth
属性,这会改变正在上传的文件本身的大小,而我想要的只是预览文件的大小更小?
// this function is invoked in a forEach loop as part of a wider code block related to the individual files from a file <input> element
function showFiles(file) {
let previewImage = new Image();
// Set <img> src attribute
previewImage.src = URL.createObjectURL(file);
// get the original width and height values of the thumbnail using the decode() method
previewImage.decode().then((response) => {
// get image dimensions for validations
let w = previewImage.naturalWidth;
let h = previewImage.naturalHeight;
let imgs = document.querySelectorAll('img') // redeclare under new var name inside promise
}).catch((encodingError) => {
// Do something with the error.
});
} // end of showfiles(file)