Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any function like getimagesize() php in javascript?

I have create upload file , but I have stack when I want to validation that content is image or not, because if validate extension only we can manipulate with fake content and valid extension.

is there function similar getimagesize() php in javascript?

like image 210
viyancs Avatar asked Sep 11 '26 04:09

viyancs


1 Answers

In some of the more modern browsers you can load an image into a canvas context (this doesn't actually have to be displayed on the page) and get the dimensions from that.

I did something like this in a CMS I built to allow the image to be scanned for certain colours without it having to be uploaded to a server first:

$('section.content form input[name=image]').change(function(){
    file = this.files[0];

    if(file.type.match(/image.*/))
    {
        var img = document.createElement('img');
        // add this into an onload, as it takes time (albeit very little) to load the image into the DOM object
        img.onload = function(){
            canv = document.getElementById('product_image');
            if(!canv || !canv.getContext)
                return; // problem getting the canvas element

            // get the canvas context that we'll be using and the width of the canvas & image
            var ctx = canv.getContext('2d');
            var width = img.width;
            var height = img.height;
        };
        // put the file into the img object, triggering the img onload handler above
        var reader = new FileReader();
        reader.onload = function(e) {img.src = e.target.result};
        reader.readAsDataURL(file);
    }
});
like image 88
Ashley Sheridan Avatar answered Sep 13 '26 18:09

Ashley Sheridan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!