CodeBlanks Logo Icon CodeBlanks

Image processing

Learn to process and display selected images.

Image processing

You take the uri value of the picked image and show it on the screen. The source prop of the Image component takes an object: { uri: photoUri }. This object carries the local file path of the image. All images picked from the gallery or taken with the camera are shown this way.

When the image is loaded you know its size: result.assets[0].width and result.assets[0].height. You can use these values for styling. To show high-resolution images small you use the resizeMode prop. cover crops the image to fill the container, contain fits the image inside the container.

resizeMode

The resizeMode prop sets how the image is sized. cover spreads the image over the whole container; overflowing parts are cropped. contain keeps the image size; the parts that do not fit stay empty. stretch forces the image to the container size; the ratio breaks.

The most common choice is cover; the image spreads over the whole container, no empty space. For square images like avatars cover works well. For gallery images contain is more suitable; the image size is preserved. resizeMode can also be added to styles: resizeMode: 'cover'.

Practice Show the picked image

Complete the empty showImage function. It takes uri as a parameter. Return <Image source={{{ uri }}} style={{{ width: 200, height: 200, resizeMode: 'cover' }}}} />.

Starter code

App.js
import { Image } from 'react-native';

export function showImage(uri) {
  // show the image in a 200x200 container with cover
}

Sample solution

App.js
return (
  <Image
    source={{ uri }}
    style={{ width: 200, height: 200, resizeMode: 'cover' }}
  />
);

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the Image source

Question
<Image source={____} style={{ width: 200, height: 200 }} />
Answer
<Image source={{ uri: photoUri }} style={{ width: 200, height: 200 }} />

Explanation: source takes an object; uri carries the image path.

2 Which resizeMode fills the container with a high-resolution image?

App.js
<Image resizeMode={??} />
  • repeat
  • stretch
  • cover Correct answer
  • center

Explanation: cover fills the container; overflow is cropped.

3 Match each field to its meaning

Term Meaning
uri Image path
width Image width
height Image height
canceled Cancel state

All lessons in Advanced