【问题标题】:Replace the image in "<input>" by a new one with the reduced size将“<input>”中的图像替换为尺寸减小的新图像
【发布时间】:2022-02-09 19:21:53
【问题描述】:

首先JS不是我常用的语言,如果问题不是很清楚,请见谅。

我一直在测试用于压缩用户上传到&lt;input&gt; 的图像的代码,压缩的 JS 代码运行良好,但我不知道如何替换他们在“输入”中选择的文件" 由我刚刚生成的压缩文件。

我想这样做是因为&lt;input&gt; 在表单中,因此我可以将图像压缩上传到服务器。

这里是 JS fot 压缩:

const MAX_WIDTH = 300;
const MAX_HEIGHT = 200;
const MIME_TYPE = "image/jpeg";
const QUALITY = 0.8;
const input = document.getElementById("img-1");

input.onchange = function (ev) {
    const file = ev.target.files[0]; // get the file
    const blobURL = URL.createObjectURL(file);
    const img = new Image();
    img.src = blobURL;
    img.onerror = function () {
        URL.revokeObjectURL(this.src);
        // Handle the failure properly
        console.log("Cannot load image");
    };
    img.onload = function () {
        URL.revokeObjectURL(this.src);
        const [newWidth, newHeight] = calculateSize(img, MAX_WIDTH, MAX_HEIGHT);
        const canvas = document.createElement("canvas");
        canvas.width = newWidth;
        canvas.height = newHeight;
        const ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, newWidth, newHeight);
        canvas.toBlob(
            blob => {
                // Do something with img in my case show in Frontend
                displayInfo('Original file', file);
                displayInfo('Compressed file', blob);
            },
            MIME_TYPE,
            QUALITY);

        // Only for testing and see results
        document.getElementById("pruebas-tam").append(canvas);
    };
};

【问题讨论】:

  • 您的&lt;input&gt;&lt;input type='file' 吗? (暗示是这样)出于浏览器安全原因,您不能更改 type='file' 值。
  • 没错,我读过,但我不想选择文件,我只想将他上传的文件更改为相同但压缩的文件。
  • 您可以在提交中重建表单数据,以便您上传新文件数据而不是输入中的文件。见developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
  • @Twisty 这似乎是一个可行的选择,但令我惊讶的是,一个必须相当普遍的问题没有标准解决方案。我会试试你的推荐,谢谢!

标签: javascript html jquery


【解决方案1】:

经过多次测试,我设法找到了解决方案,将这些行添加到我们有“blob”的地方,我们可以用新的压缩图像替换输入。该解决方案基于使用 Blob 创建文件,然后将其分配给 DataTransfer,最后将其分配回 Input。

displayInfo('Original file', file);
displayInfo('Compressed file', blob);

// Here is where we convert the blob into a file and put inside DataTransfer
let newfile = new File([blob], "filename.ext",{type:MIME_TYPE, 
lastModified:new Date().getTime()});
let container = new DataTransfer();
container.items.add(newfile);
input.files = container.files;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 2014-07-03
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 2015-01-27
    相关资源
    最近更新 更多