Skip to content

Instantly share code, notes, and snippets.

@apcurran
Created June 21, 2021 22:01
Show Gist options
  • Save apcurran/c87232352df6d06c44b504e0adccb79e to your computer and use it in GitHub Desktop.
Save apcurran/c87232352df6d06c44b504e0adccb79e to your computer and use it in GitHub Desktop.
Get image dimensions before uploading a file
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Img Upload With Dimensions</title>
</head>
<body>
<input class="file-input-btn" type="file" name="" id="">
<script>
"use strict";
const fileBtn = document.querySelector(".file-input-btn");
const uploadBtn = document.querySelector(".upload-btn");
async function getImgFile(event) {
try {
const file = event.target.files[0];
const fileAsDataUrl = window.URL.createObjectURL(file);
const imgDimensions = await getImgDimensions(fileAsDataUrl);
console.log(imgDimensions);
} catch (err) {
console.error(err);
}
}
const getImgDimensions = (dataUrl) => new Promise(resolve => {
const img = new Image();
img.onload = () => {
resolve({
width: img.width,
height: img.height
});
};
img.src = dataUrl;
});
fileBtn.addEventListener("change", getImgFile);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment