अपलोड से पहले फ़ाइल का आकार, छवि चौड़ाई और ऊंचाई प्राप्त करें


98

मैं अपनी वेबसाइट पर अपलोड करने से पहले फ़ाइल का आकार, छवि ऊंचाई और चौड़ाई कैसे प्राप्त कर सकता हूं, jQuery या जावास्क्रिप्ट के साथ?


2
यह लिंक बहुत उपयोगी है: developer.mozilla.org/en-US/docs/Web/API/FileReader/…
स्टारडस्ट

1
यहाँ फ़ाइल नाम होने का कदम ट्यूटोरियल द्वारा एक कदम, टाइप करें और आकार codepedia.info/...
सतिंदर सिंह

आपके सवाल के लिए धन्यवाद । ममनून
मोहम्मद मीरहम्मद 17

जवाबों:


174

एकाधिक चित्र जानकारी डेटा पूर्वावलोकन के साथ अपलोड करते हैं

HTML5 और फ़ाइल API का उपयोग करना

URL API का उपयोग करके उदाहरण

चित्र स्रोत ब्लॉब ऑब्जेक्ट का प्रतिनिधित्व करने वाला एक 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 का उपयोग करके उदाहरण

मामले में आपको लंबे बेस 6464 एन्कोडेड डेटा स्ट्रिंग्स के रूप में छवियों के स्रोतों की आवश्यकता होती है
<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>
  


1
@SMC caniuse.com/fileapi केवल हाल ही में फ़ाइल API का समर्थन करता है। मैं एक बार
देखूंगा

जब कॉल वैल्यू रीडर रीडर में i का मान एलर्ट किया जाता है, तो यह रैंडम इंक्रीमेंट दिखाता है! 4 फाइलों के लिए जैसे कि अलर्ट किया गया मान 0 3 2 1 था। क्या कोई समझा सकता है?
फ्रीरनर

@freerunner आपकी फाइलें अलग-अलग आकार की हैं, इसलिए एक ही समय में लोड नहीं होती हैं।
रोको सी। बुल्जन

अफसोस की बात यह है कि छवि को दो बार लोड करने की आवश्यकता है। यह बेहतर होगा यदि हम फ़ाइल प्रकार जैसी फ़ाइल गुणों के रूप में चौड़ाई और ऊंचाई प्राप्त कर सकें।
MrFox

1
की तरह लग रहा developer.mozilla.org/en-US/docs/...
WebBrother

8

यदि आप jQuery सत्यापन प्लगइन का उपयोग कर सकते हैं तो आप ऐसा कर सकते हैं:

एचटीएमएल:

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

फ़ंक्शन को ab onload फ़ंक्शन के रूप में पास किया गया है।

यहां से कोड लिया गया है


इस 'फील' में 'यह' का कोई मूल्य नहीं है। इसे एलीमेंट करने के लिए एलीमेंट में बदल दिया जाना चाहिए।
जेटलीज

एकाधिक फ़ाइल चयन के लिए इसे कैसे प्राप्त करें?
शैक निजामुद्दीन

7

डेमो

निश्चित नहीं है कि यह वही है जो आप चाहते हैं, लेकिन सिर्फ सरल उदाहरण:

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

3

यहाँ एक छवि फ़ाइल चुनने का एक शुद्ध जावास्क्रिप्ट उदाहरण है, इसे प्रदर्शित करना, छवि गुणों के माध्यम से लूप करना, और फिर छवि को कैनवास से IMG टैग में पुन: आकार देना और फिर से आकार की छवि प्रकार को jpeg में सेट करना है।

यदि आप कैनवास छवि में शीर्ष छवि पर राइट क्लिक करते हैं, और सेव फ़ाइल अस चुनें, तो यह पीएनजी प्रारूप में डिफ़ॉल्ट होगा। यदि आप दाईं ओर क्लिक करते हैं, और फ़ाइल को निचली छवि के रूप में सहेजते हैं, तो यह JPEG प्रारूप में डिफ़ॉल्ट होगा। चौड़ाई में 400px से अधिक किसी भी फ़ाइल को चौड़ाई में 400px तक घटाया जाता है, और मूल फ़ाइल की ऊँचाई आनुपातिक होती है।

एचटीएमएल

<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 टैग में नीचे की छवि पर राइट क्लिक करने के समान ही विकल्प नहीं देगा।


1

जहां तक ​​मुझे पता है कि ऐसा करने का एक आसान तरीका नहीं है क्योंकि जावास्क्रिप्ट / JQuery के पास स्थानीय फाइल सिस्टम तक पहुंच नहीं है। Html 5 में कुछ नई विशेषताएं हैं जो आपको कुछ मेटा डेटा जैसे फ़ाइल आकार की जांच करने की अनुमति देती हैं, लेकिन मुझे यकीन नहीं है कि आप वास्तव में छवि आयाम प्राप्त कर सकते हैं।

यहाँ एक लेख है जिसे मैंने html 5 सुविधाओं के बारे में पाया है, और IE के लिए एक काम है जिसमें ActiveX नियंत्रण का उपयोग करना शामिल है। http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html


1

इसलिए मैंने उन अलग-अलग चीजों के साथ प्रयोग करना शुरू कर दिया जो कि FileReader API को पेश करना था और DATA URL के साथ IMG टैग बना सकता था।

दोष: यह मोबाइल फोन पर काम नहीं करता है, लेकिन यह 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>

(कम से एक jsfiddle पर यह देखने http://jsfiddle.net/eD2Ez/530/ )
(मूल jsfiddle है कि मैं पर करने पर जोड़ा देखना http://jsfiddle.net/eD2Ez/ )


0

एक काम 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));
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.