在提交服务器之前,图像压缩
我试图在上传到服务器之前从客户端压缩图像。 我的目标是在文件输入中捕获图像,压缩它,然后在另一个文件输入字段(ImageInput)中添加压缩图像作为值,该值将在帖子中提交给服务器。
图像被压缩,但是ImageInput输入没有获得图像的值。它发布一个空图像
<script>
function process() {
const file = document.querySelector("#upload").files[0];
if (!file) return;
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
const imgElement = document.createElement("img");
imgElement.src = event.target.result;
imgElement.onload = function (e) {
const canvas = document.createElement("canvas");
const MAX_WIDTH = 400;
const scaleSize = MAX_WIDTH / e.target.width;
canvas.width = MAX_WIDTH;
canvas.height = e.target.height * scaleSize;
const ctx = canvas.getContext("2d");
ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);
const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");
// you can send srcEncoded to the server
alert(srcEncoded)
document.querySelector("#output").src = srcEncoded;
// my file input which I want to give a value of the compressed image
document.getElementById('ImageInput').value = srcEncoded;
};
};
}
</script>
I'm trying to compress images from the client side before uploading to the server.
My goal is to capture the image in a file input, Compress it, and then add the compressed image as a value in another file input field(ImageInput) which will be submitted to the server in a POST.
The Image is being compressed, But ImageInput input does not get the value of the image. It posts an empty image
<script>
function process() {
const file = document.querySelector("#upload").files[0];
if (!file) return;
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
const imgElement = document.createElement("img");
imgElement.src = event.target.result;
imgElement.onload = function (e) {
const canvas = document.createElement("canvas");
const MAX_WIDTH = 400;
const scaleSize = MAX_WIDTH / e.target.width;
canvas.width = MAX_WIDTH;
canvas.height = e.target.height * scaleSize;
const ctx = canvas.getContext("2d");
ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);
const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");
// you can send srcEncoded to the server
alert(srcEncoded)
document.querySelector("#output").src = srcEncoded;
// my file input which I want to give a value of the compressed image
document.getElementById('ImageInput').value = srcEncoded;
};
};
}
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论