Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react - get width/height of image to process

I was wondering how to get the height and width of an image if I'm rendering it react style so I can process it to flip it to portrait mode if the width is larger than the height.

Example: https://codesandbox.io/s/k9kwv0kp93

Example code:

index.js

import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

const styles = {
  fontFamily: 'sans-serif',
  textAlign: 'center',
};

const App = () => (
  <div style={styles}>
    <Hello name="CodeSandbox" />
    <h2>Start editing to see some magic happen {'\u2728'}</h2>
  </div>
);

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

Hello.js

import React, {Component} from 'react';

export default class Hello extends Component
{
  constructor()
  {
    super();
    this.state = {img: null}

    this.get_image = this.get_image.bind(this);
  }

  get_image() 
  {
    let img = <img src="http://via.placeholder.com/350x150" alt="" />;
    //manipulate here maybe
    this.setState({
      img
    })
  }

  render()
  {
    return (
      <div>
        <button onClick={this.get_image}>Click me</button>
        test
        {this.state.img}
      </div>
    )
  }
}
like image 757
A. L Avatar asked Nov 30 '22 22:11

A. L


1 Answers

I encountered the same issue, I was able to get the img height and width using ref and onLoad().


Class component version (with 'old' ref usage):


render() {
   return (
     <img
        src='https://via.placeholder.com/150'
        ref={el => this.imgEl = el}
        onLoad={() => console.log(this.imgEl.naturalHeight)} // print 150
     /> 
  )
}

Class component version (with 'new' ref):

import * as React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  imgEl = React.createRef();

  render() {
    return (
      <img
        src="https://via.placeholder.com/150"
        ref={this.imgEl}
        onLoad={() => console.log(this.imgEl.current.naturalHeight)} // print 150
      />
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Functional component version:

import React from "react";
import ReactDOM from "react-dom";

function App() {
  const imgElement = React.useRef(null);

  return (
    <img
      src="https://via.placeholder.com/150"
      ref={imgElement}
      onLoad={() => console.log(imgElement.current.naturalHeight)} // print 150
    />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Also you should use img.naturalHeight

like image 52
Pierre Ferry Avatar answered Dec 04 '22 10:12

Pierre Ferry