作為檔案上傳器的一部分,我有一些影像預覽功能,可以在上傳之前顯示影像。在此程序中,影像預覽使用htmlImageElement.decode()回傳承諾的方法,因此可以在影像上進行各種前端驗證等。此方法在與來自檔案元素的檔案相關decode()的回圈中呼叫的函式內運行。forEach()<input>
背景關系
即使我將每次上傳的檔案數限制為 10 個,因為允許使用大檔案,如果用戶附加 10 個(大)檔案,則影像預覽器在影像渲染方面以及從洗掉任何影像時都會滯后預覽器。
問題
有沒有辦法減少圖片預覽的檔案大小,而不影響要上傳的圖片的檔案大小?
您可以向建構式添加寬度和高度引數,new Image()即想要只是預覽檔案的大小更小嗎?new Image(300,300)naturalHeightnaturalWidth
// 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)
uj5u.com熱心網友回復:
畫布可用于創建原始影像的調整大小的克隆,然后使用畫布 blob作為預覽源:
// 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://www.uj5u.com/qianduan/520185.html
上一篇:如何將影像拆分為4個三角形
