LoginSignup
18
16

More than 5 years have passed since last update.

ブラウザ上でtype=fileのinputでアップされた画像の縦横サイズを取得する

Last updated at Posted at 2017-12-21

入力画面で、アップされた画像に対するパラメータを設定する機能を実装することになりそうなので予備調査。

type="file"にアップされたファイルの画像サイズを取得するには、
FileReaderオブジェクトのreadAsDataURLを使って読みこんだデータをImageオブジェクトのsrcに入れてやればサイズが取得できるみたい。

<script>
  function fileload() {
    if ( ! file.files[0] ){
      return;
    }   
    image = new Image();
    reader = new FileReader();
    reader.onloadend = function() {
      image.src = reader.result;
      image.onload = function() {
        result = {width: image.naturalWidth, height: image.naturalHeight};
        console.log(result);
      }   
    }   
    reader.readAsDataURL(file.files[0]);
  }   
</script>
<input type="file" id="file" onchange="fileload()">

参考:
JavaScriptで縮小画像の作成
FileReader.readAsDataURL()
Image

追記:

コメントで @gtk2k さんに教えて頂きました。

<script>
  function fileload() {
    if ( ! file.files[0] ){
      return;
    }
    image = new Image();
    image.onload = function() {
      result = {width: image.naturalWidth, height: image.naturalHeight};
      console.log(result);
    }
    image.src = URL.createObjectURL(file.files[0]);
  }
</script>
<input type="file" id="file" onchange="fileload()">

URL.createObjectURLでもとれるようです。
こちらの方が短くてシンプルですね。

18
16
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
16