I get this code that compress images from input element, this seems to works fine, the image is reduced at MAX_WIDTH, but my question is about the real size of the compressed image, i created a new File from the output (srcEncoded) and the size seems to be bigger than the original file. What's wrong with this? Thanks in advance.
function process() {
const file = document.querySelector("#upload").files[0];
console.log(file)
console.log("file size:", file['size']);
if (!file) return;
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(event){
const imgElement = document.createElement("img");
imgElement.src = event.target.result;
document.querySelector("#input").src = event.target.result;
imgElement.onload = function(e) {
const canvas = document.createElement("canvas");
const MAX_WIDTH = 350;
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);
console.log(e.target);
const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");
console.log(srcEncoded)
document.querySelector("#output").src = srcEncoded;
let outputFile = new File([srcEncoded], {type: 'image/jpg'});
console.log(outputFile)
}
}
}
body {
padding: 20px;
background: #e6f2ff;
}
input,
button {
font-size: 60px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<title>Resize Images Before Upload</title>
</head>
<body>
<input type="file" id="upload" accept=".jpg, .jpeg, .png" />
<button onclick="process()">Process</button>
<div>
<img id="input" />
</div>
<div>
<img id="output" />
</div>
<script src="app.js"></script>
</body>
</html>