Matthew
Matthew

Reputation: 2246

Get dimensions of image with React

I need to get the dimensions of an image with React. I found a library called react-measure that computes measurements of React components. It works, but I can't get it to fire when the image has loaded. I need to get it to fire when the image loads so I get accurate dimensions and not 0 x 157 or something like that.

I tried using the onLoad Image Event to detect when the image has loaded, but I didn't get satisfactory results. Essentially what I've done is when the image has loaded (handleImageLoaded() has been called), change the hasLoaded state property to true. I know for a fact that hasLoaded has been changed to true because it says so: Image Loaded: true.

What I noticed is that I can calculate the dimensions for only images that have been cached...

Here is a demo video: cl.ly/250M2g3X1k21

Is there a better, more concise way of retrieving dimensions properly with React?

Here is the code:

import React, {Component} from 'react';
import Measure from '../src/react-measure';
class AtomicImage extends Component {

    constructor() {
        super();
        this.state = {
            hasLoaded: false,
            dimensions: {}
        };
        this.onMeasure = this.onMeasure.bind(this);
        this.handleImageLoaded = this.handleImageLoaded.bind(this);
    }

    onMeasure(dimensions) {
        this.setState({dimensions});
    }

    handleImageLoaded() {
        this.setState({hasLoaded: true});
    }

    render() {

        const {src} = this.props;
        const {hasLoaded, dimensions} = this.state;
        const {width, height} = dimensions;

        return(
            <div>
                <p>Dimensions: {width} x {height}</p>
                <p>Image Loaded: {hasLoaded ? 'true' : 'false'}</p>
                <Measure onMeasure={this.onMeasure} shouldMeasure={hasLoaded === true}>
                    <div style={{display: 'inline-block'}}>
                        <img src={src} onLoad={this.handleImageLoaded}/>
                    </div>
                </Measure>
            </div>
        );
    }
}

export default AtomicImage;

Here is the parent code. It's not really important—just passes src to the AtomicImage element:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import AtomicImage from './AtomicImage';

class App extends Component {

  constructor() {
    super();
    this.state = {src: ''}
    this.handleOnChange = this.handleOnChange.bind(this);
  }

  handleOnChange(e) {
    this.setState({src: e.target.value});
  }

  render() {

    const {src} = this.state;
    return (
      <div>
        <div>
          <input onChange={this.handleOnChange} type="text"/>
        </div>
        <AtomicImage src={src} />
      </div>
    )
  }

}

ReactDOM.render(<App />, document.getElementById('app'));

Upvotes: 40

Views: 92727

Answers (4)

Andrii Krupa
Andrii Krupa

Reputation: 11

Another one way to get image dimension is to use react-image-size npm package with hook

eg.

import { useImageSize } from 'react-image-size';

function App() {
  const [dimensions, { loading, error }] = useImageSize('https://example.com/image.jpg');

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error}</div>;
  }

  return (
    <div>
      <p>Width: {dimensions?.width}</p>
      <p>Height: {dimensions?.height}</p>
    </div>
  );
}

Upvotes: 1

Alireza Soltani Neshan
Alireza Soltani Neshan

Reputation: 359

Also you can get image dimension with Blob file. Read this answer or you can use following sample to get image width and height.

const imageBitmap: ImageBitmap = await createImageBitmap(blob); // Blob file
const { width, height } = imageBitmap;

Upvotes: 3

Jason Henriksen
Jason Henriksen

Reputation: 69

The accepted answer is wrong for me. I'm getting the correct result with this for the onImgLoad() method:

      noteImgSize(img){
        this.imgOrigH=img.nativeEvent.srcElement.naturalHeight
        this.imgOrigW=img.nativeEvent.srcElement.naturalWidth
        this.imgOrigRatio=this.imgOrigH/this.imgOrigW
      }

Side Note, unrelated to this: Use Mobx and never have to call setState() ever again!

Upvotes: 1

Kokovin Vladislav
Kokovin Vladislav

Reputation: 10421

way of retrieving dimensions

You can achieve your goal just by js: through offsetHeight, offsetWidth. In order to get the img's dimensions, img must be visible. You can't get dimensions from a cached img.

example: https://jsbin.com/jibujocawi/1/edit?js,output

class AtomicImage  extends Component {
   constructor(props) {
        super(props);
        this.state = {dimensions: {}};
        this.onImgLoad = this.onImgLoad.bind(this);
    }
    onImgLoad({target:img}) {
        this.setState({dimensions:{height:img.offsetHeight,
                                   width:img.offsetWidth}});
    }
    render(){
        const {src} = this.props;
        const {width, height} = this.state.dimensions;

        return (<div>
                dimensions width{width}, height{height}
                <img onLoad={this.onImgLoad} src={src}/>
                </div>
               );
    }
}

Upvotes: 64

Related Questions