Подтвердить что ты не робот

Проверьте ширину и высоту изображения перед загрузкой с помощью Javascript

У меня есть JPS с формой, в которой пользователь может поместить изображение:

<div class="photo">
    <div>Photo (max 240x240 and 100 kb):</div>
    <input type="file" name="photo" id="photoInput" onchange="checkPhoto(this)"/>
</div>

Я написал это js:

function checkPhoto(target) {
    if(target.files[0].type.indexOf("image") == -1) {
        document.getElementById("photoLabel").innerHTML = "File not supported";
        return false;
    }
    if(target.files[0].size > 102400) {
        document.getElementById("photoLabel").innerHTML = "Image too big (max 100kb)";
        return false;
    }
    document.getElementById("photoLabel").innerHTML = "";
    return true;
}

который отлично работает, чтобы проверить тип и размер файла. Теперь я хочу проверить ширину и высоту изображения, но я не могу этого сделать.
Я пробовал с target.files[0].width, но я получаю undefined. Другими способами я получаю 0.
Любые предложения?

4b9b3361

Ответ 1

Файл это просто файл, вам нужно создать изображение так:

var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            alert(this.width + " " + this.height);
        };
        img.src = _URL.createObjectURL(file);
    }
});

Демо: http://jsfiddle.net/4N6D9/1/

Я так понимаю, вы понимаете, что это поддерживается только в нескольких браузерах. В основном, Firefox и Chrome, теперь могут быть оперными.

PS Метод URL.createObjectURL() был удален из интерфейса MediaStream. Этот метод был объявлен устаревшим в 2013 году и заменен путем назначения потоков для HTMLMediaElement.srcObject. Старый метод был удален, потому что он менее безопасен, требуя вызова URL.revokeOjbectURL() для завершения потока. Другие пользовательские агенты устарели (Firefox) или удалили (Safari) эту функцию.

Для получения дополнительной информации, пожалуйста, обратитесь сюда.

Ответ 2

Я согласен. Как только он будет загружен куда-то, пользовательский браузер может получить доступ, тогда его довольно легко получить размер. Поскольку вам нужно дождаться загрузки изображения, вам нужно подключиться к событию onload для img.

var width, height;

var img = document.createElement("img");
img.onload = function() {
    // `naturalWidth`/`naturalHeight` aren't supported on <IE9. Fallback to normal width/height
    // The natural size is the actual image size regardless of rendering.
    // The 'normal' width/height are for the **rendered** size.

    width  = img.naturalWidth  || img.width;
    height = img.naturalHeight || img.height; 

    // Do something with the width and height
}

// Setting the source makes it start downloading and eventually call `onload`
img.src = "http://your.website.com/userUploadedImage.jpg";

Ответ 3

На мой взгляд, идеальный ответ, который вам необходим, это

var reader = new FileReader();

//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {

//Initiate the JavaScript Image object.
var image = new Image();

//Set the Base64 string return from FileReader as source.
image.src = e.target.result;

//Validate the File Height and Width.
image.onload = function () {
  var height = this.height;
  var width = this.width;
  if (height > 100 || width > 100) {
    alert("Height and Width must not exceed 100px.");
    return false;
  }
  alert("Uploaded image has valid Height and Width.");
  return true;
};

Ответ 4

function validateimg (ctrl) {

        var fileUpload = $("#txtPostImg")[0];


        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
        if (regex.test(fileUpload.value.toLowerCase())) {

            if (typeof (fileUpload.files) != "undefined") {

                var reader = new FileReader();

                reader.readAsDataURL(fileUpload.files[0]);
                reader.onload = function (e) {

                    var image = new Image();

                    image.src = e.target.result;
                    image.onload = function () {

                        var height = this.height;
                        var width = this.width;
                        console.log(this);
                        if ((height >= 1024 || height <= 1100) && (width >= 750 || width <= 800)) {
                            alert("Height and Width must not exceed 1100*800.");
                            return false;
                        }
                        alert("Uploaded image has valid Height and Width.");
                        return true;
                    };
                }
            } else {
                alert("This browser does not support HTML5.");
                return false;
            }
        } else {
            alert("Please select a valid Image file.");
            return false;
        }
    }

Ответ 5

function uploadfile(ctrl) {
    var validate = validateimg(ctrl);

    if (validate) {
        if (window.FormData !== undefined) {
            ShowLoading();
            var fileUpload = $(ctrl).get(0);
            var files = fileUpload.files;


            var fileData = new FormData();


            for (var i = 0; i < files.length; i++) {
                fileData.append(files[i].name, files[i]);
            }


            fileData.append('username', 'Wishes');

            $.ajax({
                url: 'UploadWishesFiles',
                type: "POST",
                contentType: false,
                processData: false,
                data: fileData,
                success: function(result) {
                    var id = $(ctrl).attr('id');
                    $('#' + id.replace('txt', 'hdn')).val(result);

                    $('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();

                    HideLoading();
                },
                error: function(err) {
                    alert(err.statusText);
                    HideLoading();
                }
            });
        } else {
            alert("FormData is not supported.");
        }

    }

Ответ 6

Присоедините функцию к методу onchange типа входного файла /onchange = "validateimg (this)"/

   function validateimg(ctrl) { 
        var fileUpload = ctrl;
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
        if (regex.test(fileUpload.value.toLowerCase())) {
            if (typeof (fileUpload.files) != "undefined") {
                var reader = new FileReader();
                reader.readAsDataURL(fileUpload.files[0]);
                reader.onload = function (e) {
                    var image = new Image();
                    image.src = e.target.result;
                    image.onload = function () {
                        var height = this.height;
                        var width = this.width;
                        if (height < 1100 || width < 750) {
                            alert("At least you can upload a 1100*750 photo size.");
                            return false;
                        }else{
                            alert("Uploaded image has valid Height and Width.");
                            return true;
                        }
                    };
                }
            } else {
                alert("This browser does not support HTML5.");
                return false;
            }
        } else {
            alert("Please select a valid Image file.");
            return false;
        }
    }