代码之家  ›  专栏  ›  技术社区  ›  pjk_ok

在文件上载预览中减小图像的文件大小,而不影响要上载的文件的大小-JavaScript

  •  0
  • pjk_ok  · 技术社区  · 2 年前

    作为文件上传器的一部分,我有一些图像预览功能,可以在上传之前显示图像。在此过程中,图像预览使用 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)
    
    0 回复  |  直到 2 年前
        1
  •  2
  •   syduki    2 年前

    A. canvas 可以用于创建原始图像的已调整大小的克隆,然后使用 canvas 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>