简体   繁体   中英

How do I save an image from expo-image-picker to expo-file-system and then render it?

I am trying to store selected images within the application, as opposed to in the image roll.

Here is what I have tried:


    await FileSystem.downloadAsync(
      imageUri, // the image uri from expo-image-picker
      FileSystem.documentDirectory + `${uuid}-image.jpg`
    )
      .then(({ uri }) => {
        console.log("Finished downloading to ", uri);
      })
      .catch((error) => {
        console.error(error);
      });

I receive the error:

Unable to download file: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"

I also tried:

    await FileSystem.writeAsStringAsync(
      FileSystem.documentDirectory + `spotPhotos/${uuid}-image.jpg`,
      image.base64
    );

This seemed to be successful in saving the image, when I tried to use the image in an ImageBackground component, however I was not successful.


<ImageBackground
        source={'data:image/png;base64'+imageFile}
        style={{ borderRadius: 5, borderColor:  'black', width: 100, flex: 1, resizeMode: "cover", justifyContent: "center" }}
      >
...
</ImageBackground>

with an error saying the folder could not be read:

getFile -> err [Error: File '/var/mobile/Containers/Data/Application/.../spotPhotos' could not be read.]

Can I save the image file itself using the uri? Do I need to convert it to base64 and back?


It seems I have been able to successfully save the image base64 encoded with the following:

    await FileSystem.writeAsStringAsync(
      FileSystem.documentDirectory + `spotPhotos/${uuid}-imagelocation.jpg`,
      image.base64
    );

and access the encoded image with:

 let imageFile = async () => {
    let uri = FileSystem.documentDirectory + "spotPhotos/" + spot.imageloc;
    let options = { encoding: FileSystem.EncodingType.Base64 };
   let base64 =  await FileSystem.readAsStringAsync(uri, options);
   return (base64);
  }

When I console.log imageFile I get a huge wall of characters, which then crashes Vscodium, even when I try to just log the first few characters with string.prototype.slice(), so I havn't been able to inspect it, but I take that to be the base64 encoded file.

When I try to reference the returned value as the source of an Image or ImageBackground component like so:

<Image style={{width: 50, height: 50}} source={{imageFile}}/>
// or 

<Image style={{width: 50, height: 50}} source={{imageFile()}}/>

// or 

<Image style={{width: 50, height: 50}} source={{uri:`data:image/png;base64,${imageFile}`}}/>
// or 

<Image style={{width: 50, height: 50}} source={{uri:`data:image/jpg;base64,${imageFile}`}}/>

I receive the warning message: invalid prop 'source' supplied to 'Image' .

I also get an error message

Error: You attempted to set the key `_65` with the value of 1 on an object 
that is meant to be immutable and has been frozen.

Since the suggestion in this post doesn't work, my issue may be with the data I am pulling from the file.

What is the proper api usage to store and access jpg files in expo-file-system?

I got this working with the following code:

useEffect(() => {
    if (data[spotIndex].image) {
      imageFile();
    }
  }, [location]);

  let imageFile = async () => {
    if (data[spotIndex].image.length > 0) {
      let uri = FileSystem.documentDirectory + data[spotIndex].image;
      let getInfo = await FileSystem.getInfoAsync(uri);
      getInfo && console.log(getInfo);
      let options = { encoding: FileSystem.EncodingType.Base64 };
      let base64 = await FileSystem.readAsStringAsync(uri, options);
      setBase64Val("data:image/jpeg;base64," + base64);
    }
  };

<ImageBackground source={{ uri: base64Val }}>

import * as MediaLibrary from "expo-media-library";
import * as FileSystem from "expo-file-system";

<TouchableOpacity onPress={downloadImage}><Text>Download</Text></TouchableOpacity>

const downloadImage = () => {
  
  FileSystem.downloadAsync(
    'http://techslides.com/demos/sample-videos/small.mp4',
    FileSystem.documentDirectory + 'small.mp4'
  )
    .then(({ uri }) => {
      console.log('Finished downloading to ', uri);
      MediaLibrary.saveToLibraryAsync(uri)
    })
    .catch(error => {
      console.error(error);
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM