选择文件时Javascript调整图像大小并上传新图像而不是原始图像

标签 javascript image upload resize

我正在尝试调整上传图像的大小,然后上传新图像。我的代码运行没有错误,我可以看到图像已成功调整大小,但不知何故上传的是原始图像而不是新创建的图像。

我猜测 e.target.files[0] = newimg;不是将上传的图像文件更改为新图像文件的正确方法。正确的做法应该是什么?

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">

            function ResizeImg(e)
            {
                const file = e.target.files[0];
                const fileName = file.name;
                const reader = new FileReader();
                reader.readAsDataURL(e.target.files[0]);
                reader.onload = event => 
                {
                    const img = new Image();
                    img.src = event.target.result;
                    img.onload = () => 
                    {
                        const elem = document.createElement('canvas');
                        const ctx = elem.getContext('2d');

                        const maxWidth = 50;
                        const maxHeight = 50;

                        const ratio = Math.min(maxWidth / img.width, maxHeight / img.height);
                        const width = img.width * ratio + .5 | 0;
                        const height = img.height * ratio + .5 | 0;

                        elem.width = width;
                        elem.height = height;

                        ctx.drawImage(img, 0, 0, width, height);
                        ctx.canvas.toBlob((blob) => 
                        {
                            const newimg = new File([blob], fileName, file);
                            e.target.files[0] = newimg;
                        });
                    }
                };
            }

    </script>
    </head>

  <body>
        <form action="upload.php" method="post" enctype="multipart/form-data">
            <input name="infile" type="file" onchange="ResizeImg(this)">
            <br><br><input type="submit" name="submit">
        </form> 
  </body>   

</html>

最佳答案

您的做法在技术上是正确的,但输入的文件是只读。所以浏览器不会让你更改这些文件。您可以做的是创建新的表单数据并在其中附加所有新图像,然后使用 fetch 发送上传以异步发送而不刷新页面。

关于选择文件时Javascript调整图像大小并上传新图像而不是原始图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54941584/

相关文章:

javascript - 动态改变弹出窗口的位置

javascript - 在圆圈中定位 DIV 元素

asp.net - 必须声明标量变量 "@Image"。将图像保存到数据库时出错

asp.net - .net Drawing.Graphics.FromImage() 返回空白黑色图像

image - 使用html5中的knockout javascript文件离线上传图像

javascript - C# DateTime - 使用 fullcalendar.io 处理时区的最佳方法?

javascript - 禁用博客中的“下一个”和“上一个”按钮

html - 试图将我的图像定位得低一点,但它会把所有东西都拖下来

c++ - OpenCV 中的 Matlab Conv2 等效项

python - Robotframework "Choose file"导致 AttributeError : module 'base64' has no attribute 'encodestring' in docker