简体   繁体   English

上传前获取文件大小,图像宽度和高度

[英]Get file size, image width and height before upload

在使用jQuery或JavaScript上传到我的网站之前,如何获取文件大小,图像高度和宽度?

Multiple images upload with info data preview 带有信息数据预览的多个图像上传

Using HTML5 and the File API 使用HTML5和File API

Example using URL API 使用URL API的示例

The images sources will be a URL representing the Blob object 图片来源将是代表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> 

Example using FileReader API 使用FileReader API的示例

In case you need images sources as long Base64 encoded data strings 如果您需要图像源作为长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> 

If you can use the jQuery validation plugin you can do it like so: 如果您可以使用jQuery验证插件,则可以这样做:

Html: HTML:

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

JavaScript: JavaScript:

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

The function is passed as ab onload function. 该函数作为ab onload函数传递。

The code is taken from here 代码是从这里获取的

Demo 演示版

Not sure if it is what you want, but just simple example: 不知道这是否是您想要的,只是一个简单的示例:

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

Here is a pure JavaScript example of picking an image file, displaying it, looping through the image properties, and then re-sizing the image from the canvas into an IMG tag and explicitly setting the re-sized image type to jpeg. 这是一个纯JavaScript的示例,该示例选择一个图像文件,显示该文件,循环显示图像属性,然后将画布中的图像重新调整为IMG标签的大小,并将调整大小后的图像类型显式设置为jpeg。

If you right click the top image, in the canvas tag, and choose Save File As, it will default to a PNG format. 如果右键单击画布标签中的顶部图像,然后选择“另存为”,则默认为PNG格式。 If you right click, and Save File as the lower image, it will default to a JPEG format. 如果右键单击,然后将文件另存为下部图像,则默认为JPEG格式。 Any file over 400px in width is reduced to 400px in width, and a height proportional to the original file. 任何宽度超过400像素的文件都会减少到400像素,并且高度会与原始文件成比例。

HTML 的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 脚本

<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>

Here is a jsFiddle: 这是一个jsFiddle:

jsFiddle Pick, display, get properties, and Re-size an image file jsFiddle选择,显示,获取属性并调整图像文件的大小

In jsFiddle, right clicking the top image, which is a canvas, won't give you the same save options as right clicking the bottom image in an IMG tag. 在jsFiddle中,右键单击顶部图像(即画布)不会为您提供与右键单击IMG标签中底部图像相同的保存选项。

So I started experimenting with the different things that FileReader API had to offer and could create an IMG tag with a DATA URL. 因此,我开始尝试FileReader API必须提供的各种功能,并可以使用数据URL创建IMG标签。

Drawback: It doesn't work on mobile phones, but it works fine on Google Chrome. 缺点:无法在手机上使用,但在Google Chrome上可以正常使用。

 $('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> 

(see this on a jsfiddle at http://jsfiddle.net/eD2Ez/530/ ) (请参见http://jsfiddle.net/eD2Ez/530/上的jsfiddle上的内容)
(see the original jsfiddle that i added upon to at http://jsfiddle.net/eD2Ez/ ) (请参阅我在http://jsfiddle.net/eD2Ez/上添加的原始jsfiddle)

As far as I know there is not an easy way to do this since Javascript/JQuery does not have access to the local filesystem. 据我所知,这不是一个简单的方法,因为Javascript / JQuery无法访问本地文件系统。 There are some new features in html 5 that allows you to check certain meta data such as file size but I'm not sure if you can actually get the image dimensions. html 5中有一些新功能,可让您检查某些元数据,例如文件大小,但是我不确定是否可以实际获取图像尺寸。

Here is an article I found regarding the html 5 features, and a work around for IE that involves using an ActiveX control. 这是我发现的有关html 5功能的文章,以及涉及使用ActiveX控件的IE解决方法。 http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html

A working jQuery validate example: 一个有效的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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM