You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

58 lines
1.6 KiB

import * as ImagePicker from 'expo-image-picker';
import { ImageManipulator, SaveFormat } from 'expo-image-manipulator';
import { imageFile } from './fileio';
import { File } from 'expo-file-system';
export async function pickOne(): Promise<string | undefined> {
const res = await ImagePicker.launchImageLibraryAsync({
mediaTypes: 'images',
quality: 0.9,
allowsMultipleSelection: false,
});
if (res.canceled || !res.assets?.length) return;
return res.assets[0].uri;
}
export async function captureOne(): Promise<string | undefined> {
const perm = await ImagePicker.requestCameraPermissionsAsync();
if (!perm.granted) return;
const res = await ImagePicker.launchCameraAsync({ quality: 0.9 });
if (res.canceled || !res.assets?.length) return;
return res.assets[0].uri;
}
export async function saveOrReplaceImage(id: string, sourceUri: string): Promise<string> {
const target = imageFile(id);
const ctx = ImageManipulator.manipulate(sourceUri);
ctx.resize({ width: 1200 });
const imageRef = await ctx.renderAsync();
const cached = await imageRef.saveAsync({
format: SaveFormat.JPEG,
compress: 0.9,
});
const tmp = new File(target.parentDirectory, `${target.name}.tmp`, target.type);
if (tmp.exists) tmp.delete();
tmp.create();
const res = await fetch(cached.uri);
const buf = await res.arrayBuffer();
tmp.write(new Uint8Array(buf));
if (target.exists) target.delete();
tmp.move(target);
return target.uri;
}
export function removeImageIfExists(id: string) {
const f = imageFile(id);
if (f.exists) f.delete();
}