development

JavaScript를 사용하여 이미지 크기 (높이 및 너비)를 얻는 방법은 무엇입니까?

big-blog 2020. 10. 3. 11:16
반응형

JavaScript를 사용하여 이미지 크기 (높이 및 너비)를 얻는 방법은 무엇입니까?


페이지의 이미지 크기를 가져 오는 jQuery 또는 순수 JS API 또는 메서드가 있습니까?


프로그래밍 방식으로 이미지를 가져오고 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';

이미지가 마크 업의 일부가 아닌 경우 유용 할 수 있습니다.


clientWidthclientHeight 는 DOM 요소의 내부 차원 (여백 및 테두리 제외)의 현재 브라우저 내 크기를 표시하는 DOM 속성입니다. 따라서 IMG 요소의 경우 보이는 이미지의 실제 치수를 얻습니다.

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

또한 (Rex와 Ian의 답변 외에도) 다음이 있습니다.

imageElement.naturalHeight

imageElement.naturalWidth

이것들은 이미지 파일 자체의 높이와 너비를 제공합니다 (단지 이미지 요소가 아님).


jQuery를 사용하고 이미지 크기를 요청하는 경우로드 될 때까지 기다려야합니다. 그렇지 않으면 0 만 얻을 수 있습니다.

$(document).ready(function() {
    $("img").load(function() {
        alert($(this).height());
        alert($(this).width());
    });
});

가장 많이 뽑은 답변 중 하나가 사용 clientWidth하고 clientHeight를 제안하기 때문에 이러한 답변에 대한 업데이트가 유용 하다고 생각합니다.

실제로 반환되는 값을 확인하기 위해 HTML5로 몇 가지 실험을 수행했습니다.

우선 이미지 API의 개요를 얻기 위해 Dash라는 프로그램을 사용했습니다. 그것은한다고 heightwidth이미지의 렌더링 및 그 높이 / 너비 naturalHeightnaturalWidth이미지의 극한 높이 / 너비 (단 HTML5이다).

높이 300, 너비 400 인 파일에서 아름다운 나비 이미지를 사용했습니다. 그리고이 자바 스크립트 :

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

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

그런 다음 높이와 너비에 대해 인라인 CSS와 함께이 HTML을 사용했습니다.

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

결과 :

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

/*Actual Rendered size*/    120                  150

그런 다음 HTML을 다음과 같이 변경했습니다.

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

즉, 인라인 스타일보다는 높이 및 너비 속성 사용

결과 :

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

/*Actual Rendered size*/     90                  115

그런 다음 HTML을 다음과 같이 변경했습니다.

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

즉, 속성과 CSS를 모두 사용하여 우선 순위를 확인합니다.

결과 :

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

/*Actual Rendered size*/    120                  150

JQuery를 사용하여 다음을 수행합니다.

var imgWidth = $("#imgIDWhatever").width();

다른 모든 사람들이 잊어 버린 것은 이미지가로드되기 전에 이미지 크기를 확인할 수 없다는 것입니다. 작성자가 게시 된 모든 메서드를 확인하면 아마도 localhost에서만 작동 할 것입니다. 여기에서 jQuery를 사용할 수 있으므로 이미지가로드되기 전에 'ready'이벤트가 발생한다는 점을 기억하십시오. $ ( '# xxx'). width () 및 .height ()는 onload 이벤트 이상에서 실행되어야합니다.


실제로로드가 완료 될 때까지 이미지의 크기를 알 수 없으므로 load 이벤트의 콜백을 사용해야 만이 작업을 수행 할 수 있습니다. 아래 코드와 같은 것 ...

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

jQuery 라이브러리 사용 -

사용 .width()하고 .height().

jQuery 너비jQuery heigth에 대해 자세히 알아보십시오 .

예제 코드-

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


좋아, 나는 그 속성을 찾으려고 시도하기 전에 이미지를로드 할 수 있도록 소스 코드를 개선했다고 생각합니다. 브라우저. 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']);
}

실제 이미지 크기를 사용하기 전에 소스 이미지를로드해야합니다. JQuery 프레임 워크를 사용하면 간단한 방법으로 실제 이미지 크기를 얻을 수 있습니다.

$("ImageID").load(function(){
  console.log($(this).width() + "x" + $(this).height())
})

대답은 정확히 내가 찾고 있던 것입니다 (jQuery에서).

var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');

JQuery 답변 :

$height = $('#image_id').height();
$width  = $('#image_id').width();

간단히 이렇게 테스트 할 수 있습니다.

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

다음을 사용할 수도 있습니다.

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;

Nicky De Maeyer가 배경 사진을 물었습니다. CSS에서 가져 와서 "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()));
}

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

최근에 플렉스 슬라이더의 오류에 대해 동일한 문제가 발생했습니다. 로딩 지연으로 인해 첫 번째 이미지의 높이가 더 작게 설정되었습니다. 그 문제를 해결하기 위해 다음 방법을 시도했는데 효과가 있습니다.

// 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';

이렇게하면 원래 너비 또는 0이 아닌 설정 한 너비에 대한 높이가 제공됩니다.


페이지가 js 또는 jquery에서 다음과 같이로드 될 때 onload 핸들러 속성을 적용 할 수 있습니다.

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

 });

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.

이것이 제 방법입니다. 도움이 되길 바랍니다. :)


2019 년에 Javascript 및 / 또는 Typescript를 사용하는 사람들에게 도움이 될 것이라고 생각했습니다.

일부 사람들이 제안한 것처럼 다음이 잘못된 것으로 나타났습니다.

let img = new Image();
img.onload = function() {
  console.log(this.width, this.height) // Error: undefined is not an object
};
img.src = "http://example.com/myimage.jpg";

이것은 정확합니다 :

let img = new Image();
img.onload = function() {
  console.log(img.width, img.height)
};
img.src = "http://example.com/myimage.jpg:;

결론:

뒤에 img, 아니라를 사용하십시오 .thisonload


imageDimensions()Promise 사용을 두려워하지 않는다면 다음 ( ) 과 같은 간단한 함수를 가질 수 있습니다 .

const imageDimensions = file => new Promise((resolve, reject) => {
  try {
    const img = new Image()    
    img.onload = () => {
      const { naturalWidth: width, naturalHeight: height } = img
      resolve({ width, height })
    }
    img.onerror = () => {
      reject('There was some problem during the image loading')
    }
    img.src = URL.createObjectURL(file)
  } catch (error) {
    reject(error)
  }
})

const getInfo = ({ target: { files } }) => {
 const [file] = files
 imageDimensions(file)
   .then(result => {
     console.info(result)
   })
   .catch(error => {
     console.error(error)
   })
}
Select an image:
<input
  type="file"
  onchange="getInfo(event)"
/>


우리는 이미지 크기를 얻고 싶다고 가정합니다. <img id="an-img" src"...">

// Query after all the elements on the page have loaded.
// Or, use `onload` on a particular element to check if it is loaded.
document.addEventListener('DOMContentLoaded', function () {
  var el = document.getElementById("an-img");

  console.log({
    "naturalWidth": el.naturalWidth, // Only on HTMLImageElement
    "naturalHeight": el.naturalHeight, // Only on HTMLImageElement
    "offsetWidth": el.offsetWidth,
    "offsetHeight": el.offsetHeight
  });

자연 치수

el.naturalWidth and el.naturalHeight will get us the natural dimensions, the dimensions of the image file.

Layout Dimensions

el.offsetWidth and el.offsetHeight will get us the dimensions at which the element is rendered on the document.


it is important to remove the browser interpreted setting from the parent div. So if you want the real image width and height you can just use

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

This is one TYPO3 Project example from me where I need the real properties of the image to scale it with the right relation.


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

this work for multiple image preview and upload . if you have to select for each of the images one by one . Then copy and past into all the preview image function and validate!!!


Before acquire element's attributes,the document page should be onload:

window.onload=function(){
    console.log(img.offsetWidth,img.offsetHeight);
}

참고URL : https://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript

반응형