skip to Main Content

I have looked around a lot … but the only thing I find is about how to DISPLAY an image in react-native

But I was looking for a way to CREATE a new image in memory, set background to black and paste two other images’ contents onto it before displaying and eventually saving it

How can this be done? Btw, I’m also using expo for my project.

Thanks!

3

Answers


  1. You can use react-native-image-generator

    import { generate } from 'react-native-image-generator';
    
    // ...
    const r = await generate(
      [{
          text: '', // empty text
          fontSize: 23,
          width: 300,
          height: 300,
          x: 50,
          y: 50,
        },
      ],
      {
        filename: 'test.png',
        width: 200,
        height: 300,
      }
    )
    
    Login or Signup to reply.
  2. Creating a new image in memory, setting its background to black, pasting other images onto it, and saving it requires a few steps. Since you mentioned Expo and React Native, we are somewhat limited in the libraries we can use, as React Native doesn’t support all the same libraries as a regular Node.js environment.

    In React Native, you’ll need a way to manipulate images. You might be able to do this with Expo’s expo-image-manipulator and expo-file-system modules, but be aware that their capabilities are somewhat limited compared to full-featured image processing libraries in other environments. Here’s a rough outline of the steps you could take:

    Prerequisites
    Make sure you have installed Expo’s expo-image-manipulator and expo-file-system modules. You can install them using npm or yarn:
    bash

    expo install expo-image-manipulator
    expo install expo-file-system
    

    Steps

    1. Load the Images: Load the images into memory. You’ll likely need URIs of the images you want to manipulate. You can use local file paths, or download images from the web and save them to the device’s local storage.

    2. Create a Black Background Image: You might need to create an image with a black background manually, or you could use a 1×1 black pixel image and resize it to the desired dimensions using expo-image-manipulator.

    3. Combine Images: Use expo-image-manipulator to overlay the other images onto your black background. The manipulateAsync function in the module allows you to perform a sequence of manipulations on an image, including resizing and overlaying images.

    4. Save the Result: Once you have your combined image, you can save it to the device’s local storage using expo-file-system. The writeAsStringAsync function allows you to write data to a URI, and you can use readAsStringAsync to read it back when you want to display it.

    Example Code
    Here’s a simplified code example to get you started:

    import React from 'react';
    import { Image } from 'react-native';
    import * as ImageManipulator from 'expo-image-manipulator';
    import * as FileSystem from 'expo-file-system';
    
    export default class App extends React.Component {
       async componentDidMount() {
       try {
        // Load and manipulate images
        const image1Uri = 'your-first-image-uri';
        const image2Uri = 'your-second-image-uri';
    
        const blackBg = await this.createBlackBackground();
        const firstImage = await ImageManipulator.manipulateAsync(image1Uri, [
        { resize: { width: blackBg.width / 2 } }
      ]);
      const secondImage = await ImageManipulator.manipulateAsync(image2Uri, [
        { resize: { width: blackBg.width / 2 } }
      ]);
    
      // Combine images
      const combinedImage = await ImageManipulator.manipulateAsync(
        blackBg.uri,
        [
          { composite: [{ position: { x: 0, y: 0 }, uri: firstImage.uri }] },
          { composite: [{ position: { x: firstImage.width, y: 0 }, uri: secondImage.uri }] }
        ]
      );
    
      // Save image
      const savedUri = FileSystem.documentDirectory + 'combinedImage.png';
      await FileSystem.writeAsStringAsync(savedUri, combinedImage.uri, { encoding: FileSystem.EncodingType.Base64 });
    
      // Now you can use savedUri to display or upload the image
    
    } catch (error) {
      console.error(error);
    }
    }
    
     async createBlackBackground() {
       // Replace this method with actual creation of black background image
       // You might need to create a black image of desired size manually
       return {
         uri: 'your-black-background-uri',
         width: desiredWidth,
         height: desiredHeight
       };
     }
    
     render() {
       return (
         <Image source={{ uri: 'file-uri-of-combined-image' }} />
       );
    }
    }
    

    Notes

    . This is a simplified and hypothetical example. You need to replace the URIs and sizes with actual values relevant to your use case.

    . Image manipulation operations may not work perfectly for all kinds of images and formats. Test thoroughly with the actual images you plan to use.

    . You might need to handle permissions for reading/writing files and accessing the camera roll or other image sources on the device.
    For a more detailed understanding and customization based on your exact needs, refer to the official documentation of the expo-image-manipulator and expo-file-system.

    Login or Signup to reply.
  3. Here is the answer of GPT, and i correct it, hope can hlep you

    To create a new image in memory with a black background and paste two other images’ contents onto it in React Native, you could use the react-native-canvas library. Here’s an example code snippet that demonstrates how to create a new canvas with a black background, load two images, and draw them onto the canvas:

    import Canvas from 'react-native-canvas';
    const canvas = useRef(null);
    
    useEffect(() => {
        const ctx = canvas.getContext('2d');
        ctx.fillStyle = 'black';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    
        const img1 = new Image();
        img1.src = 'path_to_image1'; // replace with path to your first image
        img1.onload = () => {
          ctx.drawImage(img1, 0, 0, canvas.width / 2, canvas.height);
        }
    
        const img2 = new Image();
        img2.src = 'path_to_image2'; // replace with path to your second image
        img2.onload = () => {
          ctx.drawImage(img2, canvas.width / 2, 0, canvas.width / 2, canvas.height);
        };
      }, [canvas]);
      const handleSave = () => { const savePath = 'image/png'; canvas.toDataURL(savePath); }
    
      return (
        <SafeAreaView>
          <Canvas
            ref={canvas}
            style={{ width: 500, height: 500 }}
          />
          <Button title="Save Image" onPress={handleSave} />
        <SafeAreaView/>
      );
    };
    

    This code creates a new canvas element with a black background and a size of 500×500. It then loads two images (replace with the paths to your own images), waits for them to be loaded, and draws them onto the canvas. The first image is drawn on the left half of the canvas, and the second image is drawn on the right half.

    Once the canvas is created and the images are drawn, you can display it in your app (or save it) like any other React Native component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search