Malik Naser
Malik Naser

Reputation: 83

React Native - How to get image size (width and height) from device storage?

I have a react native project built on expo. I need to view an image on screen with a style that is based on the width and height of that image. How can I get the width and height of that image?

let's say the image uri is file:///storage/emulated/0/WhatsApp/Media/WhatsApp%20Images/IMG-20200117-WA0019.jpg

A solution with a code sample is highly appreciated..

Upvotes: 5

Views: 7310

Answers (2)

nevidev
nevidev

Reputation: 143

For expo projects, you can use useImage hook from expo-image.

Example:

import {useImage} from "expo-image";

const image = useImage(imageSource);

useEffect(()=>{
  if(image){
    console.log("width", image.width);
    console.log("height", image.height);
  }
},[image])

For React Native projects other than expo, look at the other answer.

Upvotes: 0

SDushan
SDushan

Reputation: 4631

React Native Image provide getSize() to get the size of remote images.

Image.getSize('uri', (width, height) => {
  this.setState({ width, height });
});

For local images you can use resolveAssetSource()

Image.resolveAssetSource(source).width
Image.resolveAssetSource(source).height

Hope this helps you. Feel free for doubts.

Upvotes: 12

Related Questions