我有一些图像预览功能,作为文件上传器的一部分,它在上传之前显示图像。在此过程中,图像预览使用htmlImageElement.decode()方法返回承诺,以便在图像上出现各种前端验证等。此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)发布于 2022-10-22 22:54:47
可以使用画布创建原图像的大小调整的克隆,然后使用帆布团作为预览源:
// 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(() => {
// get image dimensions for validations
let w = previewImage.naturalWidth;
let h = previewImage.naturalHeight;
const W = w * 0.3, H = h * 0.3;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = W, canvas.height = H;
ctx.drawImage(previewImage, 0, 0, W, H);
canvas.toBlob((blob) => {
previewImage.src = URL.createObjectURL(blob);
document.body.append(previewImage);
});
}).catch((encodingError) => {
// Do something with the error.
});
} // end of showfiles(file)
images.addEventListener('change', (e) => {
[...e.target.files].forEach(showFiles);
});<input id="images" type="file" multiple>
https://stackoverflow.com/questions/74167214
复制相似问题