【问题标题】:How can I validate the image pixel?如何验证图像像素?
【发布时间】:2019-03-15 18:06:57
【问题描述】:

如何验证图像像素? 以下是我的代码,但仅适用于图像类型和大小。

<!DOCTYPE html>
    <html>
    <head>
    <title>Image Validation</title>
    <meta charset="utf-8">
    <title>jQuery validation plug-in - comment form example</title>
    <script src="lib/jquery.js"></script>
    <script src="js/file-validator.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/app.js"></script>
    <link rel="stylesheet" href="css/cssval.css">
    <body>
        <fieldset>
            <legend>Image</legend>
            </p>
              </li>
              <li>Choose an image file:
                  <input type='file' class='demo' data-type='image' data-max-size='2mb' />
              </li>
        </fieldset>

    </body> </html>

</head>

【问题讨论】:

  • 我试图添加这个但没有运气:document.getElementById('your_form').onsubmit = function(){ var uploadImage = document.getElementById('upload_field').value; var img = new Image(); img.src = 上传图片; img.onload = function(){ if(this.width>200||this.height>400) { alert('你的图片太大,必须小于200x400'); } } }

标签: jquery html validation


【解决方案1】:

这是与 jquery 我想你必须先预览 img 无论是否隐藏,预览后使用该代码查看 THISJsfiddle 并在预览后使用该代码

$(document).ready(function(){
 var imgWidth = $('#target').width();
 var imgHeight = $('#target').height();
 if(imgWidth > 400 || imgHeight > 200){
 alert('Your image is too big, it must be less than 200x400');
}
});

【讨论】:

  • 隐藏是什么意思?我会试试这个谢谢。
  • 我的意思是如果你不希望你的用户上传图片显示预览..只是隐藏显示:没有那个 div
【解决方案2】:

在你的脚本中使用它

var _URL = window.URL || window.webkitURL;

    function readURL(input,index) {
        if (input.files && input.files[0]) {
          var reader = new FileReader();
          reader.onload = function (e) {

               $('#user_img_preview').attr('src', e.target.result);  // You can show image preview before submit


          }
          reader.readAsDataURL(input.files[0]);
        }
    }
   $("#user_img").change(function (e) {

      // Check file is image or not
      var file, img;
      if ((file = this.files[0])) {

        var fileName = this.files[0]['name'];
        var idxDot = fileName.lastIndexOf(".") + 1;
        var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
        if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){

          readURL(this,1); 
          img = new Image();
          img.onload = function () {

              if(this.width != 100 || this.height != 110) {
                alert('Please upload proper image with exact size : 100 x 110');
              } 
          };
          img.src = _URL.createObjectURL(file);

        }else{

          alert('Only jpg/jpeg and png files are allowed!');

        }

      }
  });

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 1970-01-01
    • 2019-01-16
    • 2021-07-17
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多