JavaScript で File オブジェクトの画像のサイズを取得する方法
JavaScript で File
オブジェクトとして保持された画像ファイルのサイズ(幅・高さ)を取得する方法についてです。
Node ではなくクライアントサイドの JavaScript でのお話です。
早速結論ですが、 Image
オブジェクトを生成して src
にそのファイルの中身をセットし、 onload
コールバックが呼ばれたときにサイズを取得すれば OK です。
const img = new Image();img.onload = () => {// ここでサイズが取得できるconst size = {width: img.naturalWidth,height: img.naturalHeight,};URL.revokeObjectURL(img.src);console.log(size);};img.src = URL.createObjectURL(file);
まさにこの用途のために作られているような URL.createobjectURL()
URL.revokeObjectURL()
という便利な関数が用意されています。
多用する場合は、次のようにして async 関数化しておくと便利です。
/*** 画像ファイルのサイズをチェックする*/const imagesize = async (file) => {return new Promise((resolve, reject) => {const img = new Image();img.onload = () => {const size = {width: img.naturalWidth,height: img.naturalHeight,};URL.revokeObjectURL(img.src);resolve(size);};img.onerror = (error) => {reject(error);};img.src = URL.createObjectURL(file);});}
この方法を使うと、例えば <input type="file" />
要素にセットされた画像ファイルのサイズをクライアントサイドでかんたんにチェックすることができます:
<input type="file" id="file-input" /><script>const el = document.getElementById('file-input');// `forEach()` と async 関数は組み合わせて使えないので `Promise.all()` を使うawait Promise.all(el.files.map(async (file) => {try {// `imagesize()` で `File` オブジェクトの幅・高さが取得できるconst { width, height } = await imagesize(file);} catch (error) {// 画像以外のファイルが渡されたとき等は例外があがるthrow error;}console.log({ width, height });}));</script>