我创建了一个应用程序,在这个应用程序中,我使用 expo-camera 拍摄照片并将其保存到 MediaLibrary,但我无法重命名该照片。如何重命名照片?我尝试使用 String.slice 并更改 uri 末尾的名称,但它不起作用,因为要使用 String.slice uri 必须在拍摄照片之前创建。
我如何拍照:
takePicture = async () => {
if (this.camera) {
let photo = await this.camera.takePictureAsync();
this.setState({
image: photo.uri,
modalOpen: true
});
}
console.log(this.state.image)
}
我如何保存:
saveImage = async (image, imageName) => {
const asset = await MediaLibrary.createAssetAsync(image);
MediaLibrary.createAlbumAsync('Geocad', asset)
.then(() => {
console.log('Album created!');
})
.catch(error => {
console.log('err', error);
});
this.setState({
modalOpen: false
});
}
我尝试的:
var str = image;
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "/") indices.push(i);
}
let indexNameSlice = indices.slice(-1,)[0]
let oldImageName = image.slice(0,indexNameSlice)
let newImageName = oldImageName+'/'+imageName+'.jpg'
console.log('NEWIMAGENAME', newImageName+'/'+imageName+'.jpg')
const asset = await MediaLibrary.createAssetAsync(newImageName);
嗯,官方没有解决这个问题,所以我选择使用 fs 方式。您需要将当前图像复制到具有所需图像名称的新目录,然后基于该新目录创建资产。
const timestamp = Date.now();
const imageName = `measure-${timestamp}.jpg`;
const imgUri = FileSystem.documentDirectory + imageName;
// Save the file to the new location
await FileSystem.copyAsync({
from: measure.image, // Original URI
to: imgUri, // New location
});
// create a new asset based on the new location and save it with new custom name
const renamedAsset = await MediaLibrary.createAssetAsync(imgUri);
await MediaLibrary.createAlbumAsync("Mediciones", renamedAsset, false);