2013-11-26 3 views
0

image.width을 사용하면 화면에 나타나는 이미지 너비가 반환되고 이미지에 max-width 속성이 사용되며 그 이미지는 일부 div에 표시됩니다. 실제 이미지의 크기가 훨씬 큽니다. 실제 이미지의 너비를 얻을 수 있습니까?실제 이미지 너비 및 높이 가져 오기

+1

: 경우에 캐싱 – Steve

+0

빠른 코드 예제를 함께 보낼 수 있습니까? – j08691

답변

2

당신은 이미지의 실제 크기에 의해 얻을 수 있습니다 동일한 소스로 새 이미지를 만들고 그 크기를 얻으십시오.

FIDDLE

+0

perfecto, 좋은 삶을! –

-1

당신은 이미지의 onload 이벤트에

JS 여기

var testImg = document.getElementById('testImg'), 
    iWidth=document.getElementById('width'), 
    iHeight = document.getElementById('height'); 

    testImg.onload = function(){ 
     console.log(this); 
     iWidth.value=this.width; 
     iHeight.value=this.height; 
    }; 

가의 jsfiddle입니다 액세스해야합니다 http://jsfiddle.net/mac1175/evgP8/

+0

나는 이것이 왜 왜곡 된 이유를 알아 내려고 노력하고 있습니까? – mitch

+0

이것이 동일한 문제로 실행되고 있기 때문에 OP가 실행 중입니다. DOM 요소의 너비가 원래 이미지의 너비가 아닙니다. 여기 예가있다 : http://jsfiddle.net/65JJE/ – Steve

0

먼저 3,516,, 당신은 당신이 콜백 함수의 결과를 얻을 수 있도록 코드를 작성해야 의미 비동기식 이미지로드를 알고있다. 그런 다음 명시 적 스타일이없는 새 이미지 객체를 사용하여 (기본 이미지 크기에 맞게 크기를 조정할 수 있음) 콜백을 트리거합니다. 예를 들면 :

function whatWidth(url, onSize) { 
    var img = new Image(); 
    img.src = url; 
    img.onload = function() { 
    onSize(img.width, img.height); 
    } 
} 

// Now get the dimensions of an image ... 
whatWidth('http://icons.iconarchive.com/icons/deleket/keriyo-emoticons/256/Smiley-rofl-icon.png', 
    function(w, h) { 
    console.log('width x height: ', w, h); 
    } 
); 

// => Outputs "width x height: 256 256" 

그것은만큼,이 (어떤 이미지 객체 실제로 웹 페이지에 표시하고 무관) 이미지를 가져 오기 위해 서버에 요청을 필요로 보일 수 있지만, 있음을 주목할 필요가 url은 페이지의 이미지와 동일하므로 브라우저 캐시는 [일반적으로] 한 번의 요청 만 수행하도록합니다. 어떻게`image`을 받고

class _IconSize { 
    final int width; 
    final int height; 

    _IconSize(this.width, this.height); 
} 


class IconLoader { 
    static final IconLoader _this = new IconLoader._init(); 
    factory IconLoader() => _this; 

    // Url -> dimensions. 
    final Map<String, _IconSize> _cache = {}; 

    IconLoader._init() {} 

    void withSize(String url, void onLoaded(int width, int height)) { 
    if (_cache.containsKey(url)) { 
     onLoaded(_cache[url].width, _cache[url].height); 

    } else { 
     final ImageElement img = new ImageElement(); 
     img.onLoad.listen((_) { 
     var iconSize = new _IconSize(img.width, img.height); 
     _cache[url] = iconSize; 
     withSize(url, onLoaded); 
     }); 
     img.src = url; 
    } 
    } 
} 
0

Dart 예를

당신은 (내가 JS 언급 한 원래의 질문을 알고 있지만 논리가 동일하게 유지)을해야합니까? JS 이미지 객체입니까, DOM 요소입니까?
관련 문제