Get actual image size, after resizing it

后端 未结 3 573
春和景丽
春和景丽 2021-02-05 11:01

I have a page filled with thumbnails, resized with css to 150x150, and when I click on a thumbnail, the page dims, and The image is being shown in it\'s true sizes.

3条回答
  •  臣服心动
    2021-02-05 11:25

    @Dinesh's answer to just use the naturalHeight and naturalWidth property is great and probably should be the accepted answer.

    Just wanted to add two things here that could save people hours since I see many SO posts around this issue and have myself spent quite sometime on it.

    1. naturalHeight may return 0 or undefined if called before the image is loaded. Just setting src attribute may not mean that the image is loaded immediately. I have seen that it is best to fetch it in onload.

      $('selector')[0].onload = function() {
        alert(this.naturalHeight);
        alert(this.naturalWidth);
      }
      
    2. If not using this, just $('selector').naturalHeight may not work. You may need to access the associated DOM element i.e $('selector')[0].naturalHeight or $('selector').get(0).naturalHeight since we are using native Javascript's attribute naturalHeight. See this SO post for more details.

提交回复
热议问题