173

ユーザーが画像を配置できるフォームの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
助言がありますか?

4

10 に答える 10

259

ファイルは単なるファイルです。次のような画像を作成する必要があります。

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

デモ: http: //jsfiddle.net/4N6D9/1/

これは一部のブラウザでのみサポートされていることをご存知だと思います。主にFirefoxとChromeで、今ではオペラにもなる可能性があります。

PSURL.createObjectURL()メソッドはMediaStream インターフェースから削除されました。このメソッドは2013年に廃止され、ストリームをに割り当てることで置き換えられましたHTMLMediaElement.srcObjectURL.revokeOjbectURL()古いメソッドは安全性が低く、ストリームを終了するために呼び出しが必要なため、削除されました。他のユーザーエージェントは、この機能機能を廃止(Firefox)または削除(Safari)しました。

詳細については、こちらを参照してください

于 2012-01-18T01:22:54.737 に答える
60

私の見解では、あなたが必要としなければならない完璧な答えは

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;
  };
};
于 2017-12-13T06:04:34.783 に答える
31

同意します。ユーザーのブラウザがアクセスできる場所にアップロードされると、サイズを取得するのは非常に簡単です。画像が読み込まれるのを待つ必要があるため、のonloadイベントにフックする必要がありますimg

更新された例:


// async/promise function for retrieving image dimensions for a URL
function imageSize(url) {
    const img = document.createElement("img");

    const promise = new Promise((resolve, reject) => {
      img.onload = () => {
        // Natural size is the actual image size regardless of rendering.
        // The 'normal' `width`/`height` are for the **rendered** size.
        const width  = img.naturalWidth;
        const height = img.naturalHeight; 

        // Resolve promise with the width and height
        resolve({width, height});
      };

      // Reject promise on error
      img.onerror = reject;
    });

    // Setting the source makes it start downloading and eventually call `onload`
    img.src = url;

    return promise;
}

// How to use in an async function
(async() => {
  const imageUrl = 'http://your.website.com/userUploadedImage.jpg';
  const imageDimensions = await imageSize(imageUrl);

  console.info(imageDimensions); // {width: 1337, height: 42}
})();

古い例:

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";
于 2012-01-18T01:04:23.090 に答える
24

サイズを確認する最も簡単な方法です

let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
   alert(img.width + " " + img.height);
}

特定のサイズを確認してください。例として100x100を使用

let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
   if(img.width === 100 && img.height === 100){
        alert(`Nice, image is the right size. It can be uploaded`)
        // upload logic here
        } else {
        alert(`Sorry, this image doesn't look like the size we wanted. It's 
   ${img.width} x ${img.height} but we require 100 x 100 size image.`);
   }                
}
于 2019-11-17T02:47:29.103 に答える
4

入力タイプファイルの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;
        }
    }
于 2019-06-08T13:52:20.810 に答える
2
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;
    }
}
于 2018-09-11T09:47:29.003 に答える
2

すべてのブラウザでサポートされている画像を表示せずにプレビューするための手順を実行できます。次のjsコードは、とをチェックする方法を示しています。widthheight

var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
    var reader = new FileReader();
    reader.addEventListener("load", function () {
        var image = new Image();
        image.src = this.result as string;
        image.addEventListener('load', function () {
            console.log(`height: ${this.height}, width: ${this.width}`);
        });
                
    }, false);
            
    reader.readAsDataURL(file);
}

Mozillaのドキュメントに基づく:

このreadAsDataURLメソッドは、指定された Blobまたはの内容を読み取るために使用されますFile。読み取り操作が終了すると、readyStateDONEになり、ロードエンドがトリガーされます。その時点で、result 属性にはデータがデータとして含まれています。ファイルのデータをbase64でエンコードされた文字列として表すURL。

また、ブラウザの互換性もリストされています。

于 2020-11-26T06:09:28.473 に答える
1

    const ValidateImg = (file) =>{
        let img = new Image()
        img.src = window.URL.createObjectURL(file)
        img.onload = () => {
            if(img.width === 100 && img.height ===100){
                alert("Correct size");
                return true;
            }
            alert("Incorrect size");
            return true;
        }
    }

于 2020-03-27T15:02:20.500 に答える
1

私の場合、フォームが送信されないようにする必要もあったので、これが私のために働いた解決策です。

PreventDefaultはフォームアクションを停止し、onload関数で画像のサイズとサイズを確認します。

よろしければ、送信を許可します。

ユーザーが無効な画像を使用してフォームを送信しようとすると送信ボタンが無効になるため、有効な画像が入力されたら送信ボタンを再度有効にする必要がありました。

const validateMaxImageFileSize = (e) => {
  e.preventDefault();
  const el = $("input[type='file']")[0];

  if (el.files && el.files[0]) {
    const file = el.files[0];

    const maxFileSize = 5242880; // 5 MB
    const maxWidth = 1920;
    const maxHeight = 1080;

    const img = new Image();
    img.src = window.URL.createObjectURL(file);
    img.onload = () => {
      if (file.type.match('image.*') && file.size > maxFileSize) {
        alert('The selected image file is too big. Please choose one that is smaller than 5 MB.');
      } else if (file.type.match('image.*') && (img.width > maxWidth || img.height > maxHeight)) {
        alert(`The selected image is too big. Please choose one with maximum dimensions of ${maxWidth}x${maxHeight}.`);
      } else {
        e.target.nodeName === 'INPUT'
          ? (e.target.form.querySelector("input[type='submit']").disabled = false)
          : e.target.submit();
      }
    };
  }
};

$('form.validate-image-size').on('submit', validateMaxImageFileSize);
$("form.validate-image-size input[type='file']").on('change', validateMaxImageFileSize);
于 2021-04-08T11:57:59.483 に答える
-1
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.");
        }

    }
于 2018-09-11T09:43:52.527 に答える