2

我已经创建了上传文件,但是当我想验证内容是否为图像时,我有堆栈,因为如果仅验证扩展名,我们就可以使用假内容和有效扩展名进行操作。

javascript中是否有类似getimagesize() php的函数?

4

1 回答 1

2

在一些更现代的浏览器中,您可以将图像加载到画布上下文中(这实际上不必显示在页面上)并从中获取尺寸。

我在我构建的 CMS 中做了类似的事情,以允许扫描图像的某些颜色,而不必先将其上传到服务器:

$('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);
    }
});
于 2013-01-11T09:58:27.120 回答