복붙노트

[JQUERY] 업로드하기 전에 파일 크기, 이미지의 폭과 높이를 가져옵니다

JQUERY

업로드하기 전에 파일 크기, 이미지의 폭과 높이를 가져옵니다

해결법


  1. 1.HTML5 및 파일 API를 사용하여

    HTML5 및 파일 API를 사용하여

    이미지 소스는 Blob 객체를 나타내는 URL 될 것입니다

    CONST EL_browse = document.getElementById를 ( '검색'); const를 EL_preview = document.getElementById를 ( '미리보기'); const를 readImage = 파일 => { 만약 (! (/ ^ 이미지 \ / (PNG |? JPE g | GIF) $ /) 테스트 (file.type).) 반환 EL_preview.insertAdjacentHTML ( 'beforeend',`지원되지 않는 형식 $ {file.type} : $ {file.name}로
    `); CONST IMG 새로운 이미지를 () =; img.addEventListener ( '부하'() => { EL_preview.appendChild (IMG); EL_preview.insertAdjacentHTML ( 'beforeend',`

    $ {file.name} $ {img.width} × $ {img.height} $ {file.type} $ {Math.round (file.size / 1024)} KB
    '); window.URL.revokeObjectURL (img.src); // 무료 일부 메모리 }); img.src = window.URL.createObjectURL (파일); } EL_browse.addEventListener ( '변화'EV => { EL_preview.innerHTML = ""; // 기존 이미지와 데이터를 제거 CONST 파일 = ev.target.files; 경우 반환 경고 ( '파일 업로드가 지원되지 않음') (파일 || 파일 [0]!!) ... 파일] .forEach (readImage); }); IMG {#preview의 최대 높이 : 100 픽셀; } <입력 ID = "검색"TYPE = "파일"다중>

    긴 Base64로 데이터 문자열을 인코딩 같은 경우는 이미지 소스를 필요

    CONST EL_browse = document.getElementById를 ( '검색'); const를 EL_preview = document.getElementById를 ( '미리보기'); const를 readImage = 파일 => { 만약 (! (/ ^ 이미지 \ / (PNG |? JPE g | GIF) $ /) 테스트 (file.type).) 반환 EL_preview.insertAdjacentHTML ( 'beforeend',`

    지원되지 않는 형식 $ {file.type} : $ {file.name} '); CONST 새로운 리더의 FileReader를 () =; reader.addEventListener ( '부하'() => { CONST IMG 새로운 이미지를 () =; img.addEventListener ( '부하'() => { EL_preview.appendChild (IMG); EL_preview.insertAdjacentHTML ( 'beforeend',`
    $ {file.name} $ {img.width} × $ {img.height} $ {file.type} $ {Math.round (file.size / 1024)} KB '); }); img.src = reader.result; }); reader.readAsDataURL (파일); }; EL_browse.addEventListener ( '변화'EV => { EL_preview.innerHTML = ""; // 지우기 미리보기 CONST 파일 = ev.target.files; 경우 반환 경고 ( '파일 업로드가 지원되지 않음') (파일 || 파일 [0]!!) ... 파일] .forEach (readImage); }); IMG {#preview의 최대 높이 : 100 픽셀; } <입력 ID = "검색"TYPE = "파일"다중>


  2. 2.당신이 jQuery를 유효성 검사를 사용할 수있는 경우에 당신은 그렇게 좋아 할 수있는 플러그인 :

    당신이 jQuery를 유효성 검사를 사용할 수있는 경우에 당신은 그렇게 좋아 할 수있는 플러그인 :

    HTML :

    <input type="file" name="photo" id="photoInput" />
    

    자바 스크립트 :

    $.validator.addMethod('imagedim', function(value, element, param) {
      var _URL = window.URL;
            var  img;
            if ((element = this.files[0])) {
                img = new Image();
                img.onload = function () {
                    console.log("Width:" + this.width + "   Height: " + this.height);//this will give you image width and height and you can easily validate here....
    
                    return this.width >= param
                };
                img.src = _URL.createObjectURL(element);
            }
    });
    

    기능은 AB 온로드 함수로 전달됩니다.

    이 코드는 여기에서 가져옵니다


  3. 3.그것은 당신이 원하는,하지만 단순한 예를 무엇 확실하지 경우 :

    그것은 당신이 원하는,하지만 단순한 예를 무엇 확실하지 경우 :

    var input = document.getElementById('input');
    
    input.addEventListener("change", function() {
        var file  = this.files[0];
        var img = new Image();
    
        img.onload = function() {
            var sizes = {
                width:this.width,
                height: this.height
            };
            URL.revokeObjectURL(this.src);
    
            console.log('onload: sizes', sizes);
            console.log('onload: this', this);
        }
    
        var objectURL = URL.createObjectURL(file);
    
        console.log('change: file', file);
        console.log('change: objectURL', objectURL);
        img.src = objectURL;
    });
    

  4. 4.여기 IMG 태그에 캔버스에서 이미지를 다시 크기 조정 및 명시 적으로 JPEG에 다시 크기의 이미지 유형을 설정 한 다음 이미지 속성을 통해 반복, 그것을 표시, 이미지 파일을 따기의 순수 자바 스크립트 예제, 그리고.

    여기 IMG 태그에 캔버스에서 이미지를 다시 크기 조정 및 명시 적으로 JPEG에 다시 크기의 이미지 유형을 설정 한 다음 이미지 속성을 통해 반복, 그것을 표시, 이미지 파일을 따기의 순수 자바 스크립트 예제, 그리고.

    당신이 바로 캔버스 태그에 상단 이미지를 클릭하고 저장 파일로를 선택하는 경우, 그것은 PNG 형식으로 기본 설정됩니다. 당신은 마우스 오른쪽 버튼을 클릭, 하단 이미지로 저장 파일 경우는 JPEG 형식으로 기본 설정됩니다. 폭 400 픽셀 이상 없음 파일은 폭 400 픽셀로 축소하고, 원본 파일의 높이에 비례한다.

    <form class='frmUpload'>
      <input name="picOneUpload" type="file" accept="image/*" onchange="picUpload(this.files[0])" >
    </form>
    
    <canvas id="cnvsForFormat" width="400" height="266" style="border:1px solid #c3c3c3"></canvas>
    <div id='allImgProperties' style="display:inline"></div>
    
    <div id='imgTwoForJPG'></div>
    
    <script>
    
    window.picUpload = function(frmData) {
      console.log("picUpload ran: " + frmData);
    
    var allObjtProperties = '';
    for (objProprty in frmData) {
        console.log(objProprty + " : " + frmData[objProprty]);
        allObjtProperties = allObjtProperties + "<span>" + objProprty + ": " + frmData[objProprty] + ", </span>";
    };
    
    document.getElementById('allImgProperties').innerHTML = allObjtProperties;
    
    var cnvs=document.getElementById("cnvsForFormat");
    console.log("cnvs: " + cnvs);
    var ctx=cnvs.getContext("2d");
    
    var img = new Image;
    img.src = URL.createObjectURL(frmData);
    
    console.log('img: ' + img);
    
    img.onload = function() {
      var picWidth = this.width;
      var picHeight = this.height;
    
      var wdthHghtRatio = picHeight/picWidth;
      console.log('wdthHghtRatio: ' + wdthHghtRatio);
    
      if (Number(picWidth) > 400) {
        var newHeight = Math.round(Number(400) * wdthHghtRatio);
      } else {
        return false;
      };
    
        document.getElementById('cnvsForFormat').height = newHeight;
        console.log('width: 400  h: ' + newHeight);
        //You must change the width and height settings in order to decrease the image size, but
        //it needs to be proportional to the original dimensions.
        console.log('This is BEFORE the DRAW IMAGE');
        ctx.drawImage(img,0,0, 400, newHeight);
    
        console.log('THIS IS AFTER THE DRAW IMAGE!');
    
        //Even if original image is jpeg, getting data out of the canvas will default to png if not specified
        var canvasToDtaUrl = cnvs.toDataURL("image/jpeg");
        //The type and size of the image in this new IMG tag will be JPEG, and possibly much smaller in size
        document.getElementById('imgTwoForJPG').innerHTML = "<img src='" + canvasToDtaUrl + "'>";
    };
    };
    
    </script>
    

    여기 jsFiddle입니다 :

    jsFiddle는, 표시, 선택 속성을 얻고, 이미지 파일을 다시 크기

    jsFiddle에서 오른쪽 캔버스 상단 이미지를 클릭, 오른쪽 클릭으로 당신에게 IMG 태그의 하단 이미지를 저장 옵션 같은를 제공하지 않습니다.


  5. 5.지금까지 내가 자바 스크립트 때문에이 작업을 수행하는 쉬운 방법이없는 알고 / JQuery와 로컬 파일 시스템에 액세스 할 수 없습니다. 거기 당신은 파일 크기와 같은 특정 메타 데이터를 확인할 수 있습니다 HTML 5의 새로운 기능은 있지만 실제로 이미지 크기를 얻을 수 있는지 확실하지 않습니다.

    지금까지 내가 자바 스크립트 때문에이 작업을 수행하는 쉬운 방법이없는 알고 / JQuery와 로컬 파일 시스템에 액세스 할 수 없습니다. 거기 당신은 파일 크기와 같은 특정 메타 데이터를 확인할 수 있습니다 HTML 5의 새로운 기능은 있지만 실제로 이미지 크기를 얻을 수 있는지 확실하지 않습니다.

    여기가 HTML 5 개 기능에 대한 발견 기사 및 ActiveX 컨트롤을 사용하여 포함 IE의 작업 주위입니다. http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html


  6. 6.그래서 난을 FileReader API가 제공했다 및 데이터 URL을 가진 IMG 태그를 만들 수있는 여러 가지 실험을 시작했다.

    그래서 난을 FileReader API가 제공했다 및 데이터 URL을 가진 IMG 태그를 만들 수있는 여러 가지 실험을 시작했다.

    단점 : 그것은 휴대 전화에서 작동하지 않지만, 구글 크롬에서 잘 작동합니다.

    $ ( "입력"). 변화 (함수 () { var에 FR 새로운을 FileReader를 =; fr.onload = 함수 () { var에 IMG 새로운 이미지 =; img.onload = 함수 () { // 나는 이미지를로드 및 파일 리더의 목적이다 폭과 SRC, 등의 모든 속성을 완벽하게 제어 할, 수 있습니다. $ 아약스 ({URL : img.src, 비동기 : 거짓, 성공 : 기능 (결과) { $ ( "# 결과"). html로 ( "독서의 이미지, PLEASE WAIT ...") $ ( "# 결과") HTML ( "").; ( "완료 읽기 이미지") CONSOLE.LOG; }}); }; img.src = fr.result; }; fr.readAsDataURL (this.files [0]); }); <스크립트 SRC = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

    를 볼 수있는 파일을 선택하십시오. -
    (100 % 성공률 크롬에서 성공적으로 테스트)

    (http://jsfiddle.net/eD2Ez/530/에서 jsfiddle에 참조) (내가 http://jsfiddle.net/eD2Ez/에 따라 추가로 그 원래 jsfiddle 참조)


  7. 7.실제로 동작의 jQuery 유효성 검사 예 :

    실제로 동작의 jQuery 유효성 검사 예 :

       $(function () {
            $('input[type=file]').on('change', function() {
                var $el = $(this);
                var files = this.files;
                var image = new Image();
                image.onload = function() {
                    $el
                        .attr('data-upload-width', this.naturalWidth)
                        .attr('data-upload-height', this.naturalHeight);
                }
    
                image.src = URL.createObjectURL(files[0]);
            });
    
            jQuery.validator.unobtrusive.adapters.add('imageminwidth', ['imageminwidth'], function (options) {
                var params = {
                    imageminwidth: options.params.imageminwidth.split(',')
                };
    
                options.rules['imageminwidth'] = params;
                if (options.message) {
                    options.messages['imageminwidth'] = options.message;
                }
            });
    
            jQuery.validator.addMethod("imageminwidth", function (value, element, param) {
                var $el = $(element);
                if(!element.files && element.files[0]) return true;
                return parseInt($el.attr('data-upload-width')) >=  parseInt(param["imageminwidth"][0]);
            });
    
        } (jQuery));
    
  8. from https://stackoverflow.com/questions/12570834/get-file-size-image-width-and-height-before-upload by cc-by-sa and MIT license