问题
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?
来源:https://stackoverflow.com/questions/62763209/how-do-i-save-a-picture-from-expo-image-picker-to-expo-file-system-and-then-rend