input要素で指定した画像がpngファイルか確認し、pngファイルだった場合にその幅と高さをコンソールに出力しています。
<html>
<head>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input accept="image/*" type="file" id="uploadImage">
<p><img id="thumbnail" src=""></p>
</form>
<script>
uploadImage.onchange = event => {
const [file] = uploadImage.files
if (file) {
let reader = new FileReader();
reader.onload = (e) => {
let encodedData = btoa(
Array.from(
new Uint8Array(e.target.result),
x => String.fromCharCode(x)
).join('')
);
thumbnail.src = `data:image/png;base64,${encodedData}`;
const header = new Uint8Array(e.target.result.slice(0, 8));
const headerHexStr = header.reduce((a, c) => a + (a === '' ? '' : ' ') + c.toString(16).toUpperCase().padStart(2, '0'), '');
const magicNumber = '89 50 4E 47 0D 0A 1A 0A';
if (headerHexStr === magicNumber)
{
let dataView = new DataView(e.target.result, 0x08);
let width = dataView.getUint32(0x08, false);
let height = dataView.getUint32(0x0C, false);
console.log(width);
console.log(height);
}
}
reader.readAsArrayBuffer(file);
}
}
</script>
</body>
</html>