Programing

JavaScript로 이미지의 실제 너비와 높이를 얻으시겠습니까?

lottogame 2020. 3. 25. 08:18
반응형

JavaScript로 이미지의 실제 너비와 높이를 얻으시겠습니까? (Safari / Chrome에서)


jQuery 플러그인을 작성 중입니다.

Safari에서 Javascript로 실제 이미지 너비와 높이를 얻으려면 어떻게합니까?

다음은 Firefox 3, IE7 및 Opera 9에서 작동합니다.

var pic = $("img")

// need to remove these in of case img-element has set width and height
pic.removeAttr("width"); 
pic.removeAttr("height");

var pic_real_width = pic.width();
var pic_real_height = pic.height();

그러나 Safari 및 Google Chrome과 같은 웹킷 브라우저 값은 0입니다.


웹킷 브라우저는 이미지가로드 된 후 height 및 width 속성을 설정합니다. 시간 초과를 사용하는 대신 이미지의 onload 이벤트를 사용하는 것이 좋습니다. 다음은 간단한 예입니다.

var img = $("img")[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        pic_real_width = this.width;   // Note: $(this).width() will not
        pic_real_height = this.height; // work for in memory images.
    });

CSS가 이미지의 크기에 미치는 영향을 피하기 위해 위의 코드는 이미지의 메모리 사본을 만듭니다. 이것은 FDisk가 제안한 매우 영리한 솔루션 입니다.

naturalHeightnaturalWidthHTML5 속성을 사용할 수도 있습니다 .


HTML5naturalHeightand naturalWidth속성을 사용하십시오 .

예를 들면 다음과 같습니다.

var h = document.querySelector('img').naturalHeight;

IE9 +, Chrome, Firefox, Safari 및 Opera ( 통계 )에서 작동합니다.



function getOriginalWidthOfImg(img_element) {
    var t = new Image();
    t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src;
    return t.width;
}

이미지 또는 이미지 치수 속성에서 스타일을 제거 할 필요는 없습니다. 자바 스크립트로 요소를 만들고 생성 된 객체 너비를 얻으십시오.


근본적인 문제는 WebKit 브라우저 (Safari 및 Chrome)가 JavaScript 및 CSS 정보를 병렬로로드한다는 것입니다. 따라서 CSS의 스타일 효과가 계산되기 전에 JavaScript가 실행되어 잘못된 답변을 반환 할 수 있습니다. jQuery에서 해결책은 document.readyState == 'complete'가 될 때까지 기다리는 것입니다.

jQuery(document).ready(function(){
  if (jQuery.browser.safari && document.readyState != "complete"){
    //console.info('ready...');
    setTimeout( arguments.callee, 100 );
    return;
  } 
  ... (rest of function) 

너비와 높이가 먼 한 ... 수행중인 작업에 따라 테두리 및 패딩과 같은 오프셋 너비와 오프셋 높이가 필요할 수 있습니다.


onloadWebKit 캐시에서 이미지가로드 된 경우 이벤트가 발생하지 않는 문제에 대해 허용되는 답변에 대해 많은 토론이 있습니다.

필자의 경우 onload캐시 된 이미지에 대해 발생하지만 높이와 너비는 여전히 0입니다. 간단한 setTimeout문제가 해결되었습니다.

$("img").one("load", function(){
    var img = this;
    setTimeout(function(){
        // do something based on img.width and/or img.height
    }, 0);
});

onload캐시에서 이미지가로드 된 경우에도 이벤트가 발생 하는 이유에 대해 말할 수 없습니다 (jQuery 1.4 / 1.5의 개선?). 그래도이 문제가 계속 발생하면 내 대답과 var src = img.src; img.src = ""; img.src = src;기술 의 조합 이 작업.

(나의 목적으로 이미지의 속성이나 CSS 스타일에서 미리 정의 된 치수에 대해서는 신경 쓰지 않지만 Xavi의 답변에 따라 치수를 제거하거나 이미지를 복제 할 수 있습니다.)


이것은 window.onload이벤트 내에서 발사하여 나를 위해 작동합니다 (사파리 3.2) .

$(window).load(function() {
  var pic = $('img');

  pic.removeAttr("width"); 
  pic.removeAttr("height");

  alert( pic.width() );
  alert( pic.height() );
});

DOM을 전혀 망칠 필요없이 프로그래밍 방식으로 이미지를 얻고 자바 스크립트를 사용하여 치수를 확인할 수 있습니다.

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

어떤 약 image.naturalHeightimage.naturalWidth속성?

Chrome, Safari 및 Firefox에서는 꽤 많은 버전에서 잘 작동하지만 IE8 또는 IE9에서는 전혀 작동하지 않는 것 같습니다.


실제 이미지 깜박임없이 실제 크기를 얻는 방법 :

(function( $ ){
   $.fn.getDimensions=function(){
         alert("First example:This works only for HTML code without CSS width/height definition.");
         w=$(this, 'img')[0].width;
         h=$(this, 'img')[0].height;

         alert("This is a width/height on your monitor: " + $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);

         //This is bad practice - it shows on your monitor
         $(this, 'img')[0].removeAttribute( "width" );
         $(this, 'img')[0].removeAttribute( "height" );
         alert("This is a bad effect of view after attributes removing, but we get right dimensions: "+  $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);
         //I'am going to repare it
         $(this, 'img')[0].width=w;
         $(this, 'img')[0].height=h;
         //This is a good practice - it doesn't show on your monitor
         ku=$(this, 'img').clone(); //We will work with a clone
         ku.attr( "id","mnbv1lk87jhy0utrd" );//Markup clone for a final removing
         ku[0].removeAttribute( "width" );
         ku[0].removeAttribute( "height" );
         //Now we still get 0
         alert("There are still 0 before a clone appending to document: "+ $(ku)[0].width+"/"+$(ku)[0].height);
         //Hide a clone
         ku.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'}); 
         //A clone appending
         $(document.body).append (ku[0]);
         alert("We get right dimensions: "+ $(ku)[0].width+"/"+$(ku)[0].height);
         //Remove a clone
         $("#mnbv1lk87jhy0utrd").remove();

         //But a next resolution is the best of all. It works in case of CSS definition of dimensions as well.
         alert("But if you want to read real dimensions for image with CSS class definition outside of img element, you can't do it with a clone of image. Clone method is working with CSS dimensions, a clone has dimensions as well as in CSS class. That's why you have to work with a new img element.");
         imgcopy=$('<img src="'+ $(this, 'img').attr('src') +'" />');//new object 
         imgcopy.attr( "id","mnbv1lk87jhy0aaa" );//Markup for a final removing
         imgcopy.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'});//hide copy 
         $(document.body).append (imgcopy);//append to document 
         alert("We get right dimensions: "+ imgcopy.width()+"/"+imgcopy.height());
         $("#mnbv1lk87jhy0aaa").remove();


   }
})( jQuery );

$(document).ready(function(){

   $("img.toreaddimensions").click(function(){$(this).getDimensions();});
});

<img class = "toreaddimensions"와 함께 작동합니다 ...


Jquery에는 naturalWidth와 naturalHeight라는 두 가지 속성이 있으며이 방법으로 사용할 수 있습니다.

$('.my-img')[0].naturalWidth 
$('.my-img')[0].naturalHeight

여기서 my-img는 이미지를 선택하는 데 사용되는 클래스 이름입니다.


앞에서 언급했듯이 이미지가 캐시에 있으면 Xavi 응답 이 작동하지 않습니다. 이 문제는 캐시 된 이미지에서로드 이벤트를 발생시키지 않는 웹킷에 응답하므로 너비 / 높이 속성이 img 태그에 명시 적으로 설정되어 있지 않은 경우 이미지를 얻는 유일한 확실한 방법은 window.load이벤트가 시작될 때까지 기다리는 것입니다 .

window.load이벤트가 발생합니다 항상 그 어떤 속임수없이 그 후 너비 / 높이와 IMG에 접근하는 것이 안전합니다, 그래서.

$(window).load(function(){

   //these all work

   $('img#someId').css('width');
   $('img#someId').width();
   $('img#someId').get(0).style.width;
   $('img#someId').get(0).width; 

});

캐시 될 수있는 (이전에로드 된) 동적으로로드 된 이미지의 크기를 가져와야하는 경우 Xavi 메서드와 쿼리 문자열을 사용하여 캐시 새로 고침을 트리거 할 수 있습니다. 단점은 이미 캐시되어 있고 이미 사용 가능한 img에 대해 서버에 다른 요청을 유발한다는 것입니다. 바보 웹킷.

var pic_real_width   = 0,
    img_src_no_cache = $('img#someId').attr('src') + '?cache=' + Date.now();

$('<img/>').attr('src', img_src_no_cache).load(function(){

   pic_real_width = this.width;

});

PS : 당신이에 QueryString을 경우 img.src이미를, 당신이해야합니다 구문 분석 및 캐시를 지우려면 추가 PARAM를 추가합니다.


Luke Smith가 말했듯이 이미지로드는 엉망 입니다. 모든 브라우저에서 신뢰할 수있는 것은 아닙니다. 이 사실은 나에게 큰 고통을 주었다. 캐시 된 이미지는 일부 브라우저에서 이벤트를 전혀 발생시키지 않으므로 "이미지로드가 setTimeout보다 낫다"고 말한 사람들이 잘못되었습니다.

Luke Smith의 솔루션이 여기 있습니다.

그리고 jQuery 1.4에서 이러한 혼란을 처리하는 방법에 대한 흥미로운 토론 이 있습니다.

너비를 0으로 설정 한 다음 "complete"속성이 true가되고 width 속성이 0보다 커질 때까지 기다리는 것이 매우 안정적이라는 것을 알았습니다. 오류도 감시해야합니다.


$("#myImg").one("load",function(){
  //do something, like getting image width/height
}).each(function(){
  if(this.complete) $(this).trigger("load");
});

크리스의 의견에서 : http://api.jquery.com/load-event/


내 상황은 아마 조금 다릅니다. 자바 스크립트를 통해 이미지의 src를 동적으로 변경하고 있으며 새 이미지의 크기가 고정 된 컨테이너 (사진 갤러리)에 맞게 비례 적으로 조정되어야합니다. 처음에는 이미지가로드 된 후 (이미지의로드 이벤트를 통해) 너비 및 높이 속성을 제거하고 원하는 치수를 계산 한 후 재설정했습니다. 그러나 Safari 및 IE에서는 작동하지 않습니다 (IE에서 철저하게 테스트하지는 않았지만 이미지가 표시되지 않으므로 ...).

어쨌든 Safari는 이전 이미지의 크기를 유지하므로 크기는 항상 한 이미지 뒤에 있습니다. 캐시와 관련이 있다고 가정합니다. 따라서 가장 간단한 해결책은 이미지를 복제하고 DOM에 추가하는 것입니다 (DOM에 추가하고 높이를 얻는 것이 중요합니다). 이미지의 가시성 값을 hidden으로 지정하십시오 (작동하지 않으므로 표시 없음을 사용하지 마십시오). 치수를 얻은 후에 복제본을 제거하십시오.

다음은 jQuery를 사용하는 코드입니다.

// Hack for Safari and others
// clone the image and add it to the DOM
// to get the actual width and height
// of the newly loaded image

var cloned, 
    o_width, 
    o_height, 
    src = 'my_image.jpg', 
    img = [some existing image object];

$(img)
.load(function()
{
    $(this).removeAttr('height').removeAttr('width');
    cloned = $(this).clone().css({visibility:'hidden'});
    $('body').append(cloned);
    o_width = cloned.get(0).width; // I prefer to use native javascript for this
    o_height = cloned.get(0).height; // I prefer to use native javascript for this
    cloned.remove();
    $(this).attr({width:o_width, height:o_height});
})
.attr(src:src);

이 솔루션은 어떤 경우에도 작동합니다.


event.special.load캐시 된 이미지의로드 이벤트가 발생하지 않는 경우를 처리하기 위한 jQuery 플러그인이 있습니다 : http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js


최근 그래프를 나타내는 .dialog의 기본 크기를 설정하기 위해 너비와 높이를 찾아야했습니다. 내가 사용하는 해결책은 다음과 같습니다.

 graph= $('<img/>', {"src":'mySRC', id:'graph-img'});
    graph.bind('load', function (){
        wid = graph.attr('width');
        hei = graph.attr('height');

        graph.dialog({ autoOpen: false, title: 'MyGraphTitle', height:hei, width:wid })
    })

나를 위해 이것은 FF3, Opera 10, IE 8,7,6에서 작동합니다.

추신 : LightBox 또는 ColorBox와 같은 플러그인 내부에서 더 많은 솔루션을 찾을 수 있습니다.


Xavi의 대답에 추가하기 위해 Paul Irish의 github David Desandro의 gitgub는 같은 원칙에서 작동하는 imagesLoaded ()라는 함수를 제공하며 .load () 이벤트를 발생시키지 않는 일부 브라우저의 캐시 된 이미지 문제를 해결합니다 (영리한 original_src-> data_uri-> original_src 전환).

정기적으로 널리 사용 및 업데이트되므로 문제에 대한 가장 강력한 솔루션 인 IMO에 기여합니다.


이것은 캐시 된 이미지와 동적으로로드 된 이미지 모두에서 작동합니다.

function LoadImage(imgSrc, callback){
  var image = new Image();
  image.src = imgSrc;
  if (image.complete) {
    callback(image);
    image.onload=function(){};
  } else {
    image.onload = function() {
      callback(image);
      // clear onLoad, IE behaves erratically with animated gifs otherwise
      image.onload=function(){};
    }
    image.onerror = function() {
        alert("Could not load image.");
    }
  }
}

이 스크립트를 사용하려면

function AlertImageSize(image) {
  alert("Image size: " + image.width + "x" + image.height);
}
LoadImage("http://example.org/image.png", AlertImageSize);

데모 : http://jsfiddle.net/9543z/2/


imagesLoaded jquery 플러그인을 사용하여 몇 가지 해결 방법 유틸리티 기능을 수행했습니다 : https://github.com/desandro/imagesloaded

            function waitForImageSize(src, func, ctx){
                if(!ctx)ctx = window;
                var img = new Image();
                img.src = src;
                $(img).imagesLoaded($.proxy(function(){
                    var w = this.img.innerWidth||this.img.naturalWidth;
                    var h = this.img.innerHeight||this.img.naturalHeight;
                    this.func.call(this.ctx, w, h, this.img);
                },{img: img, func: func, ctx: ctx}));
            },

URL, 함수 및 컨텍스트를 전달하여 사용할 수 있습니다. 이미지가로드 된 후 기능이 수행되고 생성 된 이미지, 너비 및 높이를 반환합니다.

waitForImageSize("image.png", function(w,h){alert(w+","+h)},this)

이미지가 이미 사용 된 경우 :

  1. 이미지 시뮬레이션을 초기로 설정

    image.css ( '너비', '초기'); image.css ( '높이', '초기');

  2. 치수를 얻다

    var originalWidth = $ (this) .width (); var originalHeight = $ (this) .height ();


HTML 이미지 요소의 naturalWidth 및 naturalHeight 속성을 사용할 수 있습니다. (자세한 정보는 다음과 같습니다 ).

다음과 같이 사용하십시오.

//you need a reference to the DOM element, not a jQuery object. It would be better if you can use document.getElementByTagsName or ID or any other native method
var pic = $("img")[0];
var pic_real_width = pic.naturalWidth;
var pic_real_height = pic.naturalHeight;

버전 8 이하의 IE를 제외한 모든 브라우저에서 작동하는 것 같습니다.


원래 배치 또는 이미지를 변경하지 않으려는 기능의 경우.

$(this).clone().removeAttr("width").attr("width");
$(this).clone().removeAttr("height").attr("height);

나는 Dio의 답변을 확인했으며 그것은 나에게 효과적입니다.

$('#image').fadeIn(10,function () {var tmpW = $(this).width(); var tmpH = $(this).height(); });

모든 함수를 aso로 호출하십시오. fadeIn ()의 호출자 함수에서 이미지 크기를 처리합니다.

고마워


나는 다른 접근법을 사용한다. 이미지 객체가 사용 중일 때 단순히 Ajax를 호출하여 이미지 크기를 얻는다.

//make json call to server to get image size
$.getJSON("http://server/getimagesize.php",
{"src":url},
SetImageWidth
);

//callback function
function SetImageWidth(data) {

    var wrap = $("div#image_gallery #image_wrap");

    //remove height
     wrap.find("img").removeAttr('height');
    //remove height
     wrap.find("img").removeAttr('width');

    //set image width
    if (data.width > 635) {
        wrap.find("img").width(635);
    }
    else {
         wrap.find("img").width(data.width);
    }
}

물론 서버 측 코드 :

<?php

$image_width = 0;
$image_height = 0;

if (isset ($_REQUEST['src']) && is_file($_SERVER['DOCUMENT_ROOT'] . $_REQUEST['src'])) {

    $imageinfo = getimagesize($_SERVER['DOCUMENT_ROOT'].$_REQUEST['src']);
    if ($imageinfo) {
       $image_width=  $imageinfo[0];
       $image_height= $imageinfo[1];
    }
}

$arr = array ('width'=>$image_width,'height'=>$image_height);

echo json_encode($arr);

?>

이것은 크로스 브라우저에서 작동합니다

var img = new Image();
$(img).bind('load error', function(e)
{
    $.data(img, 'dimensions', { 'width': img.width, 'height': img.height });                    
});
img.src = imgs[i];              

를 사용하여 치수를 얻으십시오

$(this).data('dimensions').width;
$(this).data('dimensions').height;

건배!


또 다른 제안은 imagesLoaded plugin 을 사용하는 입니다.

$("img").imagesLoaded(function(){
alert( $(this).width() );
alert( $(this).height() );
});

$(document).ready(function(){
                            var image = $("#fix_img");
                            var w = image.width();
                            var h = image.height();
                            var mr = 274/200;
                            var ir = w/h
                            if(ir > mr){
                                image.height(200);
                                image.width(200*ir);
                            } else{
                                image.width(274);
                                image.height(274/ir);
                            }
                        }); 

//이 코드는 200 * 274 크기로 이미지를 표시하는 데 도움이됩니다.


선택한 이미지가로드 될 때 이벤트를 트리거하는 크로스 브라우저 솔루션은 다음과 같습니다. http://desandro.github.io/imagesloaded/ imagesLoaded () 함수 내에서 높이와 너비를 찾을 수 있습니다.


내 자신의 질문에 대한 답을 찾으려고 노력 하면서이 실에 걸려 넘어졌습니다. 로더 후 함수에서 이미지의 너비 / 높이를 얻으려고했지만 계속 0으로 나타납니다.하지만 이것이 나를 위해 작동하는 것처럼 보일 수도 있습니다.

tempObject.image = $('<img />').attr({ 'src':"images/prod-" + tempObject.id + ".png", load:preloader });
xmlProjectInfo.push(tempObject);

function preloader() {
    imagesLoaded++;
    if (imagesLoaded >= itemsToLoad) { //itemsToLoad gets set elsewhere in code
        DetachEvent(this, 'load', preloader); //function that removes event listener
        drawItems();
    }   
}

function drawItems() {
    for(var i = 1; i <= xmlProjectInfo.length; i++)
        alert(xmlProjectInfo[i - 1].image[0].width);
}

github 에서이 저장소를 확인하십시오!

Javascript를 사용하여 너비와 높이를 확인하는 좋은 예

https://github.com/AzizAK/ImageRealSize

--- 일부 의견에서 편집이 요청되었습니다.

자바 스크립트 코드 :

 function CheckImageSize(){
var image = document.getElementById("Image").files[0];
           createReader(image, function (w, h) {

                alert("Width is: " + w + " And Height is: "+h);
});            
}


  function  createReader(file, whenReady) {
        var reader = new FileReader;
        reader.onload = function (evt) {
            var image = new Image();
            image.onload = function (evt) {
                var width = this.width;
                var height = this.height;
                if (whenReady) whenReady(width, height);
            };
            image.src = evt.target.result;
        };
        reader.readAsDataURL(file);
    }

HTML 코드 :

<html>
<head>
<title>Image Real Size</title>
<script src="ImageSize.js"></script>
</head>
<body>
<input type="file" id="Image"/>
<input type="button" value="Find the dimensions" onclick="CheckImageSize()"/>
</body>
<html>

참고 URL : https://stackoverflow.com/questions/318630/get-the-real-width-and-height-of-an-image-with-javascript-in-safari-chrome

반응형