How to get image size (height & width) using JavaScript?

前端 未结 29 3009
忘了有多久
忘了有多久 2020-11-21 05:23

Are there any JavaScript or jQuery APIs or methods to get the dimensions of an image on the page?

29条回答
  •  长情又很酷
    2020-11-21 05:47

    This is an alternative answer for Node.js, that isn't likely what the OP meant, but could come in handy and seems to be in the scope of the question.

    This is a solution with Node.js, the example uses Next.js framework but would work with any Node.js framework. It uses probe-image-size NPM package to resolve the image attributes from the server side.

    Example use case: I used the below code to resolve the size of an image from an Airtable Automation script, which calls my own analyzeImage API and returns the image's props.

    import {
      NextApiRequest,
      NextApiResponse,
    } from 'next';
    import probe from 'probe-image-size';
    
    export const analyzeImage = async (req: NextApiRequest, res: NextApiResponse): Promise => {
      try {
        const result = await probe('http://www.google.com/intl/en_ALL/images/logo.gif');
    
        res.json(result);
      } catch (e) {
        res.json({
          error: true,
          message: process.env.NODE_ENV === 'production' ? undefined : e.message,
        });
      }
    };
    
    export default analyzeImage;
    

    Yields:

    {
    "width": 276,
    "height": 110,
    "type": "gif",
    "mime": "image/gif",
    "wUnits": "px",
    "hUnits": "px",
    "length": 8558,
    "url": "http://www.google.com/intl/en_ALL/images/logo.gif"
    }
    

提交回复
热议问题