Nice programing

업로드하기 전에 이미지의 크기를 확인할 수 있습니까?

nicepro 2020. 12. 29. 08:25
반응형

업로드하기 전에 이미지의 크기를 확인할 수 있습니까?


이미지를 서버에 업로드하기위한 업로드 컨트롤이 있지만 업로드하기 전에 이미지 크기가 올바른지 확인하고 싶습니다. 클라이언트 측에서 자바 스크립트로 수행 할 수있는 것이 있습니까?


양식을 제출하기 전에 확인할 수 있습니다.

window.URL = window.URL || window.webkitURL;

$("form").submit( function( e ) {
    var form = this;
    e.preventDefault(); //Stop the submit for now
                                //Replace with your selector to find the file input in your form
    var fileInput = $(this).find("input[type=file]")[0],
        file = fileInput.files && fileInput.files[0];

    if( file ) {
        var img = new Image();

        img.src = window.URL.createObjectURL( file );

        img.onload = function() {
            var width = img.naturalWidth,
                height = img.naturalHeight;

            window.URL.revokeObjectURL( img.src );

            if( width == 400 && height == 300 ) {
                form.submit();
            }
            else {
                //fail
            }
        };
    }
    else { //No file was input or browser doesn't support client side reading
        form.submit();
    }

});

이것은 최신 브라우저에서만 작동하므로 서버 측에서 치수를 확인해야합니다. 또한 클라이언트를 신뢰할 수 없으므로 어쨌든 서버 측을 확인해야하는 또 다른 이유입니다.


예, HTML5 API가이를 지원합니다.

http://www.w3.org/TR/FileAPI/

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

$("#file").change(function(e) {

    var image, file;

    if ((file = this.files[0])) {

        image = new Image();

        image.onload = function() {

            alert("The image width is " +this.width + " and image height is " + this.height);
        };

        image.src = _URL.createObjectURL(file);


    }

});​

데모 (Chrome에서 테스트 됨)


간단하게하려면 fabric.js , processing.jsMarvinJ같은 자바 스크립트 이미지 처리 프레임 워크를 사용 하세요 .

In the case of MarvinJ, simply loads the image in the client side and use the methods getWidth() and getHeight() to check the image's dimensions. Having the dimensions you can allow the file submission or notify the user about the incompatible dimension.

Example:

var image = new MarvinImage();
image.load("https://i.imgur.com/oOZmCas.jpg", imageLoaded);

function imageLoaded(){
  document.getElementById("result").innerHTML += image.getWidth()+","+image.getHeight();
}
<script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
<div id="result"></div>


Might be a bit late but here's a modern ES6 version of the accepted answer using promises

const getUploadedFileDimensions: file => new Promise((resolve, reject) => {
    try {
        let img = new Image()

        img.onload = () => {
            const width  = img.naturalWidth,
                  height = img.naturalHeight

            window.URL.revokeObjectURL(img.src)

            return resolve({width, height})
        }

        img.src = window.URL.createObjectURL(file)
    } catch (exception) {
        return reject(exception)
    }
})

You'd call it like this

getUploadedFileDimensions(file).then(({width, height}) => {
    console.log(width, height)
})

If you don't need to handle svg files and can limit yourself to newest browsers, then you can use the createImageBitmap function to make a Promise based one liner:

if(typeof createImageBitmap !== "function") {
  console.error("Your browser doesn't support this method");
  // fallback to URL.createObjectURL + <img>
}

inp.oninput = e => {
  createImageBitmap(inp.files[0])
    .then((bmp) => console.log(bmp.width, bmp.height))
    .catch(console.error);
}
<input type="file" id="inp" accept="image/*">


Give this a shot. I've used this in the past. https://github.com/valums/file-uploader

ReferenceURL : https://stackoverflow.com/questions/13572129/is-it-possible-to-check-dimensions-of-image-before-uploading

반응형