js上传图片获取图片尺寸

  • Post author:
  • Post category:其他


下面这段代码,可以实现本地上传图片,并获取图片的尺寸

<!DOCTYPE html>
<html lang="en">
  <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>Document</title>
  </head>
  <body>
    <input type="file" id="file" />
    <img src="" alt="" id="image-preview" />

    <script>
      let fileInput = document.getElementById("file");
      let preview = document.getElementById("image-preview");

      fileInput.addEventListener("change", () => {
        let file = fileInput.files[0];
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          let data = e.target.result;
          preview.src = data;
          let image = new Image();
          image.src = data;
          image.onload = function () {
            console.log(image.width, image.height);
          };
        };
      });
    </script>
  </body>
</html>

在这里插入图片描述



版权声明:本文为ssjjrr原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。