19

I want to use Image.getSize (https://facebook.github.io/react-native/docs/image.html) to get the size of my image but the first argument require the image source to be in URI but I can't use URI with static file, I can only use Require.

Therefore, is it possible is to use Image.getSize on static file or do I have to find another way?

binkpitch
  • 677
  • 1
  • 8
  • 18

4 Answers4

38

You can use resolveAssetSource (from react-native/Libraries/Image/resolveAssetSource) to get the image's size.

import resolveAssetSource from 'resolveAssetSource';

and

let icon =  require('./assets/images/icon.png'); 
let source = resolveAssetSource(icon);
// source.width, source.height`
Florent Roques
  • 2,424
  • 2
  • 20
  • 23
PTT
  • 654
  • 5
  • 6
  • Hi! I edited your code sections and put them into code blocks. You can use the `{}` button in the editor to do this yourself. Can you add a reference to the package you are mentioning here? That would make this a great answer. – Pekka Feb 13 '17 at 08:54
  • @Pekka웃, I might be wrong, but I used require : `const resolveAssetSource = require('resolveAssetSource');` – vincenth Mar 08 '17 at 15:23
  • 7
    Succeed with `import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';` – Val Dec 15 '17 at 06:33
  • I am trying to use resolveAssetSource in my code, but I am failing. The following includes an example for what I am doing: https://github.com/DylanVann/react-native-fast-image/issues/410#issuecomment-650614622 Can you explain what I am doing wrong? – Yossi Jun 28 '20 at 06:20
13

You can use Image.resolveAssetSource(source).width and Image.resolveAssetSource(source).height.

Reference in React Native docs: https://facebook.github.io/react-native/docs/image.html#resolveassetsource

Benoît Vogel
  • 316
  • 3
  • 8
10

Through official document

import { Image } from 'react-native'

const url = require('./x.png')
const image = Image.resolveAssetSource(url)

Then use image.width and image.height

duan
  • 8,515
  • 3
  • 48
  • 70
1
let path = "file:///storage/emulated/0/Pictures/xxx.jpg";
Image.getSize(path,(w,h)=>{
        console.log('w h=',w,h);
    },(err)=>{
        console.log('err....',err);
    })
Berton
  • 11
  • 1
  • Is it a good idea?I don't think so this should only work on andorid not ios. – Steve Moretz Mar 10 '21 at 17:55
  • The Image.getSize method can get only remote image dimensions not static/local image dimensions. ref [link](https://tutorialscapital.com/react-native-retrieve-remote-image-dimensions-android-ios-tutorial/) – AliRehman7141 Apr 17 '21 at 00:08