Jak uzyskać Rozmiar obrazu (wysokość i szerokość) za pomocą JavaScript?

Czy są jakieś jQuery lub pure js API lub metody, aby uzyskać wymiary obrazu na stronie?

Author: Karol Selak, 2009-03-08

23 answers

Clientwidth i clientHeight są właściwościami DOM, które pokazują bieżący rozmiar w przeglądarce wewnętrznych wymiarów elementu DOM (bez marginesu i obramowania). Tak więc w przypadku elementu IMG uzyskamy rzeczywiste wymiary widocznego obrazu.

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
 393
Author: Rex M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-21 07:22:53

Możesz programowo pobrać obraz i sprawdzić wymiary za pomocą Javascript...

var img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

Może to być przydatne, jeśli obraz nie jest częścią znaczników.

 693
Author: Josh Stodola,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-18 12:13:38

Ponadto (oprócz odpowiedzi Rexa i Iana) jest:

imageElement.naturalHeight

I

imageElement.naturalWidth

Określają wysokość i szerokość samego pliku obrazu (a nie tylko elementu obrazu).

 259
Author: olliej,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-08 23:12:05

Jeśli używasz jQuery i żądasz rozmiarów obrazów, musisz poczekać, aż się załadują, albo dostaniesz tylko zera.

$(document).ready(function() {
    $("img").load(function() {
        alert($(this).height());
        alert($(this).width());
    });
});
 106
Author: mrtsherman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-01 21:38:20

Myślę, że aktualizacja tych odpowiedzi jest przydatna, ponieważ jedna z najlepiej głosowanych odpowiedzi sugeruje użycie clientWidth i clientHeight, które moim zdaniem jest teraz przestarzałe.

Zrobiłem kilka eksperymentów z HTML5, aby zobaczyć, które wartości rzeczywiście zwracane.

Po pierwsze, użyłem programu o nazwie Dash, aby uzyskać przegląd interfejsu API obrazów. Oznacza to, że height i width są renderowaną wysokością / szerokością obrazu, a naturalHeight i naturalWidth są wewnętrzną wysokością / szerokością obrazu (i są tylko HTML5).

Użyłam zdjęcia pięknego motyla, z pliku o wysokości 300 i szerokości 400. I ten Javascript:

var img = document.getElementById("img1");

console.log(img.height,           img.width);
console.log(img.naturalHeight,    img.naturalWidth);
console.log($("#img1").height(),  $("#img1").width());

Następnie użyłem tego HTML, z wbudowanym CSS dla wysokości i szerokości.

<img style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />

Wyniki:

/*Image Element*/ height == 300         width == 400
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() == 120       width() == 150

/*Actual Rendered size*/    120                  150

Potem zmieniłem HTML na następujący:

<img height="90" width="115" id="img1" src="img/Butterfly.jpg" />

Tj. używanie atrybutów wysokości i szerokości zamiast stylów inline

Wyniki:

/*Image Element*/ height ==  90         width == 115
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() ==  90       width() == 115

/*Actual Rendered size*/     90                  115

Potem zmieniłem HTML na po:

<img height="90" width="115" style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />

Tj. używając zarówno atrybutów, jak i CSS, aby zobaczyć, co ma pierwszeństwo.

Wyniki:

/*Image Element*/ height ==  90         width == 115
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() == 120       width() == 150

/*Actual Rendered size*/    120                  150
 89
Author: paulo62,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-08 22:45:35

Używając JQuery robisz to:

var imgWidth = $("#imgIDWhatever").width();
 62
Author: Ian Suttle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-08 06:59:57

Wszyscy inni zapomnieli, że nie można sprawdzić rozmiaru obrazu przed załadowaniem. Gdy autor sprawdzi wszystkie opublikowane metody, będzie działać prawdopodobnie tylko na localhost. Ponieważ jQuery może być tutaj używany, pamiętaj, że zdarzenie 'ready' jest wywoływane przed załadowaniem obrazów. $('#xxx').szerokość () i .height() powinna być wywołana w zdarzeniu onload lub później.

 26
Author: Thinker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-10 13:54:42

Można to zrobić tylko za pomocą wywołania zwrotnego zdarzenia load, ponieważ Rozmiar obrazu nie jest znany, dopóki nie zakończy się wczytywanie. Coś jak poniższy kod...

var imgTesting = new Image();

function CreateDelegate(contextObject, delegateMethod)
{
    return function()
    {
        return delegateMethod.apply(contextObject, arguments);
    }
}

function imgTesting_onload()
{
    alert(this.width + " by " + this.height);
}


imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';
 18
Author: Lee Hesselden,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-04 11:50:29

With jQuery library-

Użyj .width() i .height().

Więcej w jQuery width i jQuery heigth.

Przykładowy Kod-

$(document).ready(function(){
    $("button").click(function()
    {
        alert("Width of image: " + $("#img_exmpl").width());
        alert("Height of image: " + $("#img_exmpl").height());
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg">
<button>Display dimensions of img</button>
 8
Author: Abrar Jahin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-30 04:53:46

Ok chłopaki, myślę, że poprawiłem kod źródłowy, aby móc załadować obraz przed próbą znalezienia jego właściwości, w przeciwnym razie wyświetli się '0 * 0', ponieważ następne polecenie zostałoby wywołane przed załadowaniem pliku do przeglądarki. Wymaga jquery...

function getImgSize(imgSrc){
    var newImg = new Image();
    newImg.src = imgSrc;
    var height = newImg.height;
    var width = newImg.width;
    p = $(newImg).ready(function(){
        return {width: newImg.width, height: newImg.height};
    });
    alert (p[0]['width']+" "+p[0]['height']);
}
 7
Author: claudio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-01 21:41:00

Przed użyciem rzeczywistego rozmiaru obrazu należy wczytać obraz źródłowy. Jeśli używasz jQuery framework możesz uzyskać rzeczywisty rozmiar obrazu w prosty sposób.

$("ImageID").load(function(){
  console.log($(this).width() + "x" + $(this).height())
})
 6
Author: sub,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-19 13:41:53

Ta odpowiedź była dokładnie tym, czego szukałem (w jQuery):

var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');
 4
Author: dev101,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:35

JQuery Odpowiedź:

$height = $('#image_id').height();
$width  = $('#image_id').width();
 2
Author: Eli Geske,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-02 07:16:44

Po prostu, możesz przetestować w ten sposób.

  <script>
  (function($) {
        $(document).ready(function() {
            console.log("ready....");
            var i = 0;
            var img;
            for(i=1; i<13; i++) {
                img = new Image();
                img.src = 'img/' + i + '.jpg';
                console.log("name : " + img.src);
                img.onload = function() {
                    if(this.height > this.width) {
                        console.log(this.src + " : portrait");
                    }
                    else if(this.width > this.height) {
                        console.log(this.src + " : landscape");
                    }
                    else {
                        console.log(this.src + " : square");
                    }
                }
            }
        });
    }(jQuery));
  </script>
 2
Author: cloudrain21,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-26 02:31:45

Możesz również użyć:

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;
 1
Author: praveenjayapal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-18 01:05:41

Nicky de Maeyer zapytał po obrazku w tle; po prostu dostaję go z css i zamieniam " url ()":

var div = $('#my-bg-div');
var url = div.css('background-image').replace(/^url\(\'?(.*)\'?\)$/, '$1');
var img = new Image();
img.src = url;
console.log('img:', img.width + 'x' + img.height); // zero, image not yet loaded
console.log('div:', div.width() + 'x' + div.height());
img.onload = function() {
  console.log('img:', img.width + 'x' + img.height, (img.width/div.width()));
}
 1
Author: Hraban,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-19 15:09:43
var img = document.getElementById("img_id");
alert( img.height + " ;; " + img .width + " ;; " + img .naturalHeight + " ;; " + img .clientHeight + " ;; " + img.offsetHeight + " ;; " + img.scrollHeight + " ;; " + img.clientWidth + " ;; " + img.offsetWidth + " ;; " + img.scrollWidth )
//But all invalid in Baidu browser  360 browser ...
 1
Author: user3496915,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-04 07:46:30

Ostatnio miałem ten sam problem z błędem w suwaku flex. Wysokość pierwszego obrazu została ustawiona na mniejszą ze względu na opóźnienie ładowania. Wypróbowałem następującą metodę rozwiązania tego problemu i zadziałało.

// create image with a reference id. Id shall be used for removing it from the dom later.
var tempImg = $('<img id="testImage" />');
//If you want to get the height with respect to any specific width you set.
//I used window width here.
tempImg.css('width', window.innerWidth);  
tempImg[0].onload = function () {
    $(this).css('height', 'auto').css('display', 'none');
    var imgHeight = $(this).height();
    // Remove it if you don't want this image anymore.
    $('#testImage').remove();
}
//append to body
$('body').append(tempImg);
//Set an image url. I am using an image which I got from google.
tempImg[0].src ='http://aspo.org/wp-content/uploads/strips.jpg';

To da ci wysokość w odniesieniu do szerokości, którą ustawiłeś, a nie oryginalną szerokość lub Zero.

 1
Author: muhammed basil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-14 14:37:51

Możesz zastosować właściwość obsługi onload, gdy strona ładuje się w js lub jquery w następujący sposób: -

$(document).ready(function(){
   var width = img.clientWidth;
   var height = img.clientHeight;

 });
 1
Author: Harkamal Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-12 09:59:18
var imgSrc, imgW, imgH;
function myFunction(image){
    var img = new Image();
    img.src = image;
    img.onload = function() {   
        return {
            src:image,
            width:this.width,
            height:this.height};
        }
    return img;
}
var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
    //Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
x.addEventListener('load',function(){
    imgSrc = x.src;
    imgW = x.width;
    imgH = x.height;
});
x.addEventListener('load',function(){
    console.log(imgW+'x'+imgH);//276x110
});
console.log(imgW);//undefined.
console.log(imgH);//undefined.
console.log(imgSrc);//undefined.
To jest moja metoda, mam nadzieję, że pomocna. :)
 1
Author: DHA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-01 13:16:28

Ważne jest, aby usunąć ustawienia interpretowane przez przeglądarkę z nadrzędnego div. Więc jeśli chcesz mieć rzeczywistą szerokość i wysokość obrazu, możesz po prostu użyć

$('.right-sidebar').find('img').each(function(){
    $(this).removeAttr("width");
    $(this).removeAttr("height");
    $(this).imageResize();
});

Oto przykład projektu TYPO3, w którym potrzebuję rzeczywistych właściwości obrazu, aby przeskalować go z odpowiednią relacją.

 0
Author: Rogoit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-12 09:45:27
function outmeInside() {
var output = document.getElementById('preview_product_image');

 if (this.height < 600 || this.width < 600) {
     output.src = "http://localhost/danieladenew/uploads/no-photo.jpg";
     alert("The image you have selected is low resloution image.Your image width=" + this.width + ",Heigh=" + this.height + ". Please select image greater or equal to 600x600,Thanks!");
 } else {
     output.src = URL.createObjectURL(event.target.files[0]);

 }
 return;

 }

 img.src = URL.createObjectURL(event.target.files[0]);
}

To działa do wielokrotnego podglądu i przesyłania obrazów . jeśli musisz wybrać dla każdego z obrazów jeden po drugim . Następnie skopiuj i wklej do wszystkich funkcji podglądu obrazu i zatwierdź!!!

 0
Author: danielad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-09 15:41:24

Przed uzyskaniem atrybutów elementu,strona dokumentu powinna zostać załadowana:

window.onload=function(){
    console.log(img.offsetWidth,img.offsetHeight);
}
 0
Author: 中国程序员,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-03 03:28:01