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

前端 未结 29 2763
忘了有多久
忘了有多久 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:45

    The thing all other have forgot is that you cant check image size before it loads. When the author checks all of posted methods it will work probably only on localhost. Since jQuery could be used here, remember that 'ready' event is fired before images are loaded. $('#xxx').width() and .height() should be fired in onload event or later.

    0 讨论(0)
  • 2020-11-21 05:45

    Let's combine everything we learned here into one simple function (imageDimensions()). It uses promises.

    // helper to get dimensions of an image
    const imageDimensions = file => 
        new Promise((resolve, reject) => {
            const img = new Image()
    
            // the following handler will fire after the successful loading of the image
            img.onload = () => {
                const { naturalWidth: width, naturalHeight: height } = img
                resolve({ width, height })
            }
    
            // and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one)
            img.onerror = () => {
                reject('There was some problem with the image.')
            }
        
            img.src = URL.createObjectURL(file)
    })
    
    // here's how to use the helper
    const getInfo = async ({ target: { files } }) => {
        const [file] = files
     
        try {
            const dimensions = await imageDimensions(file)
            console.info(dimensions)
        } catch(error) {
            console.error(error)
        }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script>
    
    Select an image:
    <input
      type="file"
      onchange="getInfo(event)"
    />
    <br />
    <small>It works offline.</small>

    0 讨论(0)
  • 2020-11-21 05:45
    function outmeInside() {
    var output = document.getElementById('preview_product_image');
    
     if (this.height < 600 || this.width < 600) {
         output.src = "http://localhost/danieladenew/uploads/no-photo.jpg";
         alert("The image you have selected is low resloution image.Your image width=" + this.width + ",Heigh=" + this.height + ". Please select image greater or equal to 600x600,Thanks!");
     } else {
         output.src = URL.createObjectURL(event.target.files[0]);
    
     }
     return;
    
     }
    
     img.src = URL.createObjectURL(event.target.files[0]);
    }
    

    this work for multiple image preview and upload . if you have to select for each of the images one by one . Then copy and past into all the preview image function and validate!!!

    0 讨论(0)
  • 2020-11-21 05:46

    it is important to remove the browser interpreted setting from the parent div. So if you want the real image width and height you can just use

    $('.right-sidebar').find('img').each(function(){
        $(this).removeAttr("width");
        $(this).removeAttr("height");
        $(this).imageResize();
    });
    

    This is one TYPO3 Project example from me where I need the real properties of the image to scale it with the right relation.

    0 讨论(0)
  • 2020-11-21 05:46

    Try

    function sizes() {
      console.log(`width: ${pic.width}, height:${pic.height}`);
    }
    <img id="pic" src="https://picsum.photos/300/150">
    <button onclick="sizes()">show size</button>

    0 讨论(0)
  • 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<void> => {
      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"
    }
    
    0 讨论(0)
提交回复
热议问题