programing

업로드 전에 파일 크기, 이미지 너비 및 높이 가져오기

elecom 2023. 10. 25. 22:34
반응형

업로드 전에 파일 크기, 이미지 너비 및 높이 가져오기

jQuery 또는 JavaScript로 웹 사이트에 업로드하기 전에 파일 크기, 이미지 높이 및 너비를 얻으려면 어떻게 해야 합니까?

정보 데이터 미리보기와 함께 여러 이미지 업로드

HTML5File API 사용

URL API 사용 예제

이미지 소스는 Blob 개체를 나타내는 URL이 됩니다.
<img src="blob:null/026cceb9-edr4-4281-babb-b56cbf759a3d">

const EL_browse  = document.getElementById('browse');
const EL_preview = document.getElementById('preview');

const readImage  = file => {
  if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )
    return EL_preview.insertAdjacentHTML('beforeend', `Unsupported format ${file.type}: ${file.name}<br>`);

  const img = new Image();
  img.addEventListener('load', () => {
    EL_preview.appendChild(img);
    EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB<div>`);
    window.URL.revokeObjectURL(img.src); // Free some memory
  });
  img.src = window.URL.createObjectURL(file);
}

EL_browse.addEventListener('change', ev => {
  EL_preview.innerHTML = ''; // Remove old images and data
  const files = ev.target.files;
  if (!files || !files[0]) return alert('File upload not supported');
  [...files].forEach( readImage );
});
#preview img { max-height: 100px; }
<input id="browse" type="file" multiple>
<div id="preview"></div>

FileReader API 사용 예제

Base64 인코딩 데이터 문자열 길이만큼 영상 소스가 필요한 경우
<img src="data:image/png;base64,iVBORw0KGg... ...lF/++TkSuQmCC=">

const EL_browse  = document.getElementById('browse');
const EL_preview = document.getElementById('preview');

const readImage = file => {
  if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) )
    return EL_preview.insertAdjacentHTML('beforeend', `<div>Unsupported format ${file.type}: ${file.name}</div>`);

  const reader = new FileReader();
  reader.addEventListener('load', () => {
    const img  = new Image();
    img.addEventListener('load', () => {
      EL_preview.appendChild(img);
      EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB</div>`);
    });
    img.src = reader.result;
  });
  reader.readAsDataURL(file);  
};

EL_browse.addEventListener('change', ev => {
  EL_preview.innerHTML = ''; // Clear Preview
  const files = ev.target.files;
  if (!files || !files[0]) return alert('File upload not supported');
  [...files].forEach( readImage );
});
#preview img { max-height: 100px; }
<input id="browse" type="file"  multiple>
<div id="preview"></div>
  

데모

원하는 것인지는 확실하지 않지만 단순한 예입니다.

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;
});

jQuery validation 플러그인을 사용할 수 있는 경우 다음과 같이 수행할 수 있습니다.

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);
        }
});

그 기능은 부하 함수로 전달됩니다.

코드는 여기서 가져온 것입니다.

다음은 이미지 파일을 선택하여 표시하고 이미지 속성을 루프링한 다음 캔버스의 이미지를 IMG 태그로 재사이징하고 재사이징된 이미지 유형을 jpeg로 명시적으로 설정하는 순수한 자바스크립트 예입니다.

캔버스 태그에서 맨 위 이미지를 마우스 오른쪽 단추로 클릭하고 다른 이름으로 파일 저장을 선택하면 기본적으로 PNG 형식이 됩니다.마우스 오른쪽 단추를 누른 후 파일 저장을 하단 이미지로 지정하면 기본적으로 JPEG 형식으로 설정됩니다.너비가 400px를 초과하는 파일은 원래 파일에 비례하는 너비와 높이가 400px로 줄어듭니다.

HTML

<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 태그에서 하단 이미지를 마우스 오른쪽 버튼으로 클릭하는 것과 동일한 저장 옵션이 제공되지 않습니다.

자바스크립트/JQuery는 로컬 파일 시스템에 접근할 수 없기 때문에 쉬운 방법이 없는 것으로 알고 있습니다.html 5에는 파일 크기와 같은 특정 메타 데이터를 확인할 수 있는 새로운 기능들이 있지만 실제로 이미지 치수를 얻을 수 있을지 잘 모르겠습니다.

여기 html 5 기능에 관한 기사와 ActiveX 컨트롤을 사용하는 IE에 대한 해결책이 있습니다.http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html

그래서 저는 FileReader API가 제공해야 하는 다양한 것들을 실험하기 시작했고 DATA URL로 IMG 태그를 만들 수 있었습니다.

단점:휴대폰에서는 작동하지 않지만 구글 크롬에서는 잘 작동합니다.

$('input').change(function() {
    
    var fr = new FileReader;
    
    fr.onload = function() {
        var img = new Image;
        
        img.onload = function() { 
//I loaded the image and have complete control over all attributes, like width and src, which is the purpose of filereader.
            $.ajax({url: img.src, async: false, success: function(result){
            		$("#result").html("READING IMAGE, PLEASE WAIT...")
            		$("#result").html("<img src='" + img.src + "' />");
                console.log("Finished reading Image");
        		}});
        };
        
        img.src = fr.result;
    };
    
    fr.readAsDataURL(this.files[0]);
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" accept="image/*" capture="camera">
<div id='result'>Please choose a file to view it. <br/>(Tested successfully on Chrome - 100% SUCCESS RATE)</div>

(http://jsfiddle.net/eD2Ez/530/) 의 jsfiddle에서 이 내용을 참조하십시오.
(http://jsfiddle.net/eD2Ez/) 에 추가한 원본 jsfiddle 참조)

작동 중인 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));

언급URL : https://stackoverflow.com/questions/12570834/get-file-size-image-width-and-height-before-upload

반응형