Reputation: 1
When I used Image.resolveAssetSource
, I was getting a null
value when using an image URL instead of a local image.
When I used onLoad
, I received {"height": 972, "width": 1296}
, which was a compressed value instead of the original dimensions {"height": 3888, "width": 5184}
. (React Native sometimes compresses images if they have a high resolution.)
In the code below, I was getting {"height": 972, "width": 1296}
in the console log instead of the original values {"height": 3888, "width": 5184}
.
import React, { useState } from 'react';
import { View, Image, Text } from 'react-native';
export default function App() {
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
const handleImageLoad = (event) => {
const { width, height } = event.nativeEvent.source;
console.log('Actual image dimensions:', { width, height });
setDimensions({ width, height });
};
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Image
source={require('./assets/DJI_20230607123846_0002_SUPR.jpg')}
onLoad={handleImageLoad}
style={{ width: 200, height: 200 }}
/>
<Text>Image dimensions: {dimensions.width} x {dimensions.height}</Text>
</View>
);
}
Upvotes: 0
Views: 18
Reputation: 704
Use Image.getSize(picUri, (width, height) => {this.setState({width, height})});
Or, try using react-native-image-size
:
npm install react-native-image-size
ImageSize.getSize(imageUrl).then((size) => {
console.log('Original dimensions:', size);
setDimensions({ width: size.width, height: size.height });
}).catch((error) => {
console.error('Error fetching dimensions:', error);
});
Upvotes: 0