JS - get image width and height from the base64 code

后端 未结 4 704
攒了一身酷
攒了一身酷 2020-11-27 14:46

I have a base64 img encoded that you can find here. How can I get the height and the width of it?

4条回答
  •  臣服心动
    2020-11-27 15:35

    I found that using .naturalWidth and .naturalHeight had the best results.

    const img = new Image();
    
    img.src = 'https://via.placeholder.com/350x150';
    
    img.onload = function() {
      const imgWidth = img.naturalWidth;
      const imgHeight = img.naturalHeight;
    
      console.log('imgWidth: ', imgWidth);
      console.log('imgHeight: ', imgHeight);
    };
    

    Docs:

    • https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalWidth
    • https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/naturalHeight

    This is only supported in modern browsers. http://www.jacklmoore.com/notes/naturalwidth-and-naturalheight-in-ie/

提交回复
热议问题