jQuery客户端调整大小,出现加载错误/获取图像的高度宽度

时间:2018-09-06 07:51:39

标签: javascript jquery

这是我的第一篇文章,所以,请保持友好 删除这些行。

<!--This 1x1 picture size workaround is a real flower-->
<img src="" id="preview" width="1" height="1">

导致以下脚本出现故障。有人可以解释我在做什么错吗?

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $('#imageFile').change(function(evt) {
        var files = evt.target.files;
        var file = files[0];
        //reader.onprogess = function(event) {
        //      document.getElementById('progressbar').innerHTML = "Progressbar";
        //      sleep 
        //    };
        if (file) {
            var reader = new FileReader();
    
            reader.onload = function(e) {
                document.getElementById('preview').src = e.target.result;
                document.getElementById('status').innerHTML = "Upload succesful";
				ResizeImage();
            };
            reader.readAsDataURL(file);
        }
    });
});

function ResizeImage() {
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        var filesToUpload = document.getElementById('imageFile').files;
        var file = filesToUpload[0];
        if (file) {

            var reader = new FileReader();
            // Set the image once loaded into file reader
            reader.onload = function(e) {

                var img = document.createElement("img");
                img.src = e.target.result;

                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);

                var MAX_WIDTH = 400;
                var MAX_HEIGHT = 400;
                var width = img.width;
                var height = img.height;
                
                if (width > height) {
                    if (width > MAX_WIDTH) {
                        height *= MAX_WIDTH / width;
                        width = MAX_WIDTH;
                    }
                } else {
                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;
                        height = MAX_HEIGHT;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, width, height);
                dataurl = canvas.toDataURL();
                document.getElementById('output').src = dataurl;
            }
            reader.readAsDataURL(file);

        }

    } else {
        alert('Not working so well in this browser');
    }
}
  </script>
</head> 
<input id="imageFile" name="imageFile" type="file" class="imageFile"  accept="image/gif, image/jpeg, image/png"/> 
<br/>
<!--This 1x1 picture size workaround is a real flower-->
<img src="" id="preview" width="1" height="1">
<p id="status">status</p>
<img src="" id="output">

0 个答案:

没有答案