programing

JavaScript를 사용하여 이미지의 실제 폭과 높이를 확인하시겠습니까?(Safari/Chrome)

yoursource 2022. 9. 23. 22:50
반응형

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입니다.

웹킷 브라우저는 이미지가 로드된 후 높이 및 너비 속성을 설정합니다.타임아웃을 사용하는 대신 이미지의 온로드 이벤트를 사용하는 것이 좋습니다.다음은 간단한 예입니다.

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가 제안하는 매우 현명한 솔루션입니다.

이 경우에도 하실 수 있습니다.naturalHeight ★★★★★★★★★★★★★★★★★」naturalWidthHTML5 html html html html

하다를 사용하세요.naturalHeight ★★★★★★★★★★★★★★★★★」naturalWidthHTML5에서 속성을 지정합니다.

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

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

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


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

이미지 또는 이미지 치수 속성에서 스타일을 제거할 필요가 없습니다.javascript를 사용하여 요소를 만들고 생성된 객체 너비를 얻습니다.

에는 '이렇게 하다'라는에 대해 onloadWebKit 캐시에서 이미지가 로드되면 이벤트가 실행되지 않습니다.

경우에는 ★★★★★★★★★★★★★★★★★★★★★★★★★.onload캐시된 이미지에 대해 기동하지만 높이와 폭은 0입니다.한 a a.setTimeout이치노

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

수긍할 수긍이 가지다.onload 1.45의 되지 않으면 내 과 "JQuery 1.4/1.5"의 을 사용할 수 .그러나 이 문제가 아직 발생하고 있는 경우는, 제 답변과var src = img.src; img.src = ""; img.src = src;기법이 통할 것이다.

(저의 목적상 이미지 속성이나 CSS 스타일 중 어느 쪽이든 미리 정의된 치수는 상관없지만, Xavi의 답변에 따라 이러한 치수는 삭제하는 것이 좋을 수 있습니다.또는 이미지를 복제합니다.)

근본적인 문제는 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) 

폭과 높이에 관한 한...수행하는 작업에 따라 오프셋 폭 및 오프셋이 필요할 수 있습니다.높이: 테두리나 패딩 등을 포함합니다.

3. 3. 3.2번에서 .window.onload 이벤트 표시:

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

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

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

Javascript를 사용하여 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.naturalHeight ★★★★★★★★★★★★★★★★★」image.naturalWidth★★★★★★★★★★★★★★★★★★?

Chrome, Safari, Firefox의 일부 버전은 정상적으로 동작하지만 IE8이나 IE9에서는 전혀 동작하지 않습니다.

Jquery에는 naturalWidth와 naturalHeight라는 두 가지 속성이 있습니다.이렇게 사용할 수 있습니다.

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

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

실제 이미지를 깜박이지 않고 정확한 실제 치수를 얻는 방법:

(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="toread dimensions...

앞서 말한 것처럼 이미지가 캐시에 있으면 사비의 답변이 작동하지 않습니다.웹킷이 캐시된 이미지에서 로드이벤트를 기동하지 않는 경우 문제는 응답합니다.따라서 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;

});

: "QueryString"img.src이미 해석하고 캐시를 클리어하기 위해 추가 파라미터를 추가해야 합니다.

Luke Smith가 말했듯이 이미지 로드는 엉망입니다.모든 브라우저에서 신뢰할 수 있는 것은 아닙니다.이 사실은 나에게 큰 고통을 주었다.캐시된 이미지는 일부 브라우저에서 이벤트를 전혀 발생시키지 않기 때문에 "이미지 로드가 set Timeout보다 낫다"는 말은 틀렸습니다.

루크 스미스의 해결책은 여기 있다.

jQuery 1.4에서는 이 문제를 어떻게 처리할지에 대한 흥미로운 논의가 있습니다.

폭을 0으로 설정한 후 "완전" 속성이 참이 되고 너비 속성이 0보다 클 때까지 기다리는 것이 매우 신뢰할 수 있습니다.오류도 주의하셔야 합니다.

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

Chris 코멘트 : http://api.jquery.com/load-event/

제 상황은 조금 다를 거예요.javascript를 통해 이미지의 src를 동적으로 변경하고 있으며, 새로운 이미지의 크기가 고정 용기(포토갤러리)에 맞도록 해야 했습니다.처음에는 로드 후(이미지 로드 이벤트) 이미지의 폭과 높이 속성을 삭제하고 원하는 치수를 계산한 후 재설정했습니다.다만, Safari나 IE에서는 동작하지 않는 경우가 있습니다(IE에서는 충분히 테스트하고 있지 않지만, 이미지가 표시되지 않기 때문에...).

어쨌든 Safari는 이전 이미지의 치수를 유지하므로 치수는 항상 한 이미지 뒤에 있습니다.캐시와 관련이 있는 것 같아요따라서 가장 간단한 해결책은 이미지를 복제하여 DOM에 추가하는 것입니다(Get과 높이를 가진 DOM에 추가하는 것이 중요합니다).이미지에 숨겨진 가시성 값을 지정합니다(작동하지 않으므로 디스플레이 없음 사용 안 함).치수를 얻은 후 클론을 제거합니다.

다음은 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);

이 솔루션은 어떤 경우에도 기능합니다.

이제 jQuery 플러그인이 있습니다.event.special.load캐시된 이미지의 로드 이벤트가 발생하지 않는 경우의 대처법:

최근에 그래프를 나타내는 .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와 같은 일부 플러그인에서 더 많은 솔루션을 찾을 수 있습니다.

사비의 대답에 덧붙이자면 폴 아이리쉬 기트허브David Desandro의 gitgub은 images라는 기능을 제공합니다.Loaded()는 동일한 원리로 동작하며 일부 브라우저의 캐시된 이미지가 .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/

이미지를 사용하여 몇 가지 회피 유틸리티 기능을 수행했습니다.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 "width", "initial"; image.css "height", "initial";

  2. 치수를 구하다

    var originalWidth = $(이것).width(); var originalHeight = $(이것).높이();

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를 제외한 모든 브라우저에서 동작하는 것 같습니다.

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;

건배!

또 다른 제안은 이미지를 사용하는 것입니다.플러그인이 로드되었습니다.

$("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/ 이미지 내에서 높이와 폭을 검색할 수 있습니다.Loaded() 함수.

내 질문에 대한 답을 찾으려다 우연히 이 실마리를 찾았다.로더 후 함수에서 이미지의 폭/높이를 구하려고 했는데 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

---일부 코멘트에서 편집이 요구되고 있습니다.

Javascript 코드:

 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>

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

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

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

반응형