Tuesday, April 30, 2019

React Native Get Remote Image Dimensions Android iOS

This tutorial explain how to get remote image dimensions in height and width in react native application. React native Image component provides a method named as getSize  which is used to get remote image dimensions in width and height.

getSize() function of Image Component In React Native :
Retrieve the width and height (in pixels) of an image prior to displaying it. This method can fail if the image cannot be found, or fails to download. In order to retrieve the image dimensions, the image may first need to be loaded or downloaded, after which it will be cached. This means that in principle you could use this method to preload images, however it is not optimized for that purpose, and may in future be implemented in a way that does not fully load/download the image data. A proper, supported way to preload images will be provided as a separate API.

Syntax : 
Image.getSize(uri, success, [failure]);

As you can see, getSize method takes three parameters:
  • uri : The location of the image.
  • success : The function that will be called if the image was successfully found and width and height retrieved.
  • failure : The function that will be called if there was an error, such as failing to retrieve the image.
Note: The Image.getSize method can get only remote image dimensions not static / local image dimensions.

React Native Get Remote Image Dimensions Android iOS


React Native Retrieve Actual Image Sizes :

Lets follow the below steps to get actual image sizes of HTTP remote image including width and height.

Step 1: Create a new react native project, if you don’t know how to create a new project in react native just follow this tutorial.

Step 2: Open App.js File in your favorite code editor and erase all code and follow this tutorial.

Step 3: Through react , react-native  packages import all required components.
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, Image, ActivityIndicator } from 'react-native';

Step 4: Implement constructor  method. Inside the constructor we have defined state object and uri parameter that helps to get image dimension and loading effect.
constructor() {
    super();
    this.state = { width: 0, height: 0, loading: true }
    this.uri = 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKLTtPpfhTVC2yJY2e8tHNzAPCqyhLC8gghOEFrsNxsGrK7BddXZNZp9Z_7A05gDWeBb2P9vx_97xqOjU6HeHgxExsPtPX4-vFvBgw4L4_EbL7sE-yxOUIgcMMMeqro393FBn3mJKpGDNf/s640/drop.png';
  }

Step 5: Implement componentDidMount lifecycle method in which getSize method will get the image width and height and update width and height state variables.
componentDidMount() {
    Image.getSize(this.uri, (width, height) => {
      this.setState({ width: width, height: height, loading: false });
    }, (error) => {
      this.setState({ loading: false });
      console.log(error);
    });
  }

Step 6 : Implement render method inside the App class and wrapped the below layout design inside the root View component.
render() {
    return (
      <View style={styles.container}>
        <View style={styles.imageContainer}>
          {
            (this.state.loading)
              ?
              <ActivityIndicator size="large" />
              :
              (<Image source={{ uri: this.uri }} style={styles.image} />)
          }
          <View style={styles.showDimensionsView}>
            <Text style={styles.text}>{this.state.width}(w) X {this.state.height}(h)</Text>
          </View>
        </View>

      </View>
    );
  }

Step 7 : Apply the below style sheet design.
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#e5e5e5",
  },
  headerText: {
    fontSize: 20,
    textAlign: "center",
    margin: 10,
    padding: 10,
    fontWeight: "bold"
  },
  imageContainer: {
    position: 'relative',
    width: 370,
    height: 250,
    justifyContent: 'center',
    alignItems: 'center'
  },
  image: {
    resizeMode: 'cover',
    width: '100%',
    height: '100%'
  },
  showDimensionsView: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0,0,0,0.6)',
    alignItems: 'center',
    paddingTop: 10,
    paddingBottom: 10,
  },
  text: {
    fontSize: 20,
    color: 'black',
    color: 'rgba(255,255,255,0.8)'
  }
});

Complete Source Code for App.js 

Lets see the complete source code that helps to get actual image sizes of HTTP remote image including width and height in react native application.

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, Image, ActivityIndicator } from 'react-native';


export default class App extends Component {

  constructor() {
    super();
    this.state = { width: 0, height: 0, loading: true }
    this.uri = 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKLTtPpfhTVC2yJY2e8tHNzAPCqyhLC8gghOEFrsNxsGrK7BddXZNZp9Z_7A05gDWeBb2P9vx_97xqOjU6HeHgxExsPtPX4-vFvBgw4L4_EbL7sE-yxOUIgcMMMeqro393FBn3mJKpGDNf/s640/drop.png';
  }


  componentDidMount() {
    Image.getSize(this.uri, (width, height) => {
      this.setState({ width: width, height: height, loading: false });
    }, (error) => {
      this.setState({ loading: false });
      console.log(error);
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.imageContainer}>
          {
            (this.state.loading)
              ?
              <ActivityIndicator size="large" />
              :
              (<Image source={{ uri: this.uri }} style={styles.image} />)
          }
          <View style={styles.showDimensionsView}>
            <Text style={styles.text}>{this.state.width}(w) X {this.state.height}(h)</Text>
          </View>
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#e5e5e5",
  },
  headerText: {
    fontSize: 20,
    textAlign: "center",
    margin: 10,
    padding: 10,
    fontWeight: "bold"
  },
  imageContainer: {
    position: 'relative',
    width: 370,
    height: 250,
    justifyContent: 'center',
    alignItems: 'center'
  },
  image: {
    resizeMode: 'cover',
    width: '100%',
    height: '100%'
  },
  showDimensionsView: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0,0,0,0.6)',
    alignItems: 'center',
    paddingTop: 10,
    paddingBottom: 10,
  },
  text: {
    fontSize: 20,
    color: 'black',
    color: 'rgba(255,255,255,0.8)'
  }
});

Screenshot :

React Native Get Remote Image Dimensions Android iOS

React Native Get Remote Image Dimensions Android iOS

This is all about React Native Get Remote Image Dimensions Android iOS. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment