52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
import * as ImagePicker from 'expo-image-picker'
|
|
|
|
import Toast from '../components/Toast'
|
|
|
|
// 定义图片项类型
|
|
|
|
type PickerBaseParams = Omit<
|
|
ImagePicker.ImagePickerOptions,
|
|
'mediaTypes' | 'allowsMultipleSelection' | 'selectionLimit'
|
|
> & {
|
|
maxImages?: number
|
|
type?: ImagePicker.MediaTypeOptions
|
|
}
|
|
|
|
type PickerUriParams = PickerBaseParams & {
|
|
resultType?: 'uri'
|
|
}
|
|
|
|
type PickerAssetParams = PickerBaseParams & {
|
|
resultType: 'asset'
|
|
}
|
|
export async function imgPicker(params: PickerUriParams | PickerAssetParams) {
|
|
const { maxImages = 1, type = ImagePicker.MediaTypeOptions.Images, resultType = 'uri', ...reset } = params
|
|
|
|
const isMultiple = maxImages > 1
|
|
|
|
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync()
|
|
if (status !== 'granted') {
|
|
Toast?.show({ title: '请开启相册权限' })
|
|
throw new Error('请开启相册权限')
|
|
}
|
|
|
|
const result = await ImagePicker.launchImageLibraryAsync({
|
|
mediaTypes: type,
|
|
// allowsEditing: true,
|
|
quality: 0.9,
|
|
allowsMultipleSelection: isMultiple,
|
|
selectionLimit: maxImages,
|
|
...reset,
|
|
})
|
|
|
|
if (result.canceled || !result.assets?.length) {
|
|
throw new Error('未选择任何图片')
|
|
}
|
|
|
|
if (resultType === 'uri') {
|
|
return result.assets.map((a) => a.uri)
|
|
}
|
|
|
|
return result.assets
|
|
}
|