如何在使用 expo-image-picker 时添加图像类型和大小限制(例如我只能选择 jpeg 类型图像和最大内存 2000kB)

Hab*_*man 5 reactjs react-native expo

我在我的 React Native 项目之一中使用图像选择器。现在,我需要在从图库中选取图像或使用相机捕获图像时添加一些限制。

我只想选择jpeg类型的图像,并且它们的内存必须小于2000kB。

可以使用 expo-image-picker 吗?提前致谢。

Deb*_*Das 10

// Install this npm
import * as FileSystem from 'expo-file-system'
import * as ImagePicker from 'expo-image-picker'

export const getFileInfo = async (fileURI: string) => {
   const fileInfo = await FileSystem.getInfoAsync(fileURI)
   return fileInfo
}

export const isLessThanTheMB = (fileSize: number, smallerThanSizeMB: number) => {
   const isOk = fileSize / 1024 / 1024 < smallerThanSizeMB
   return isOk
}


const handleUploadPhoto = async () => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsEditing: true,
        quality: 1,
      })

      if (result.cancelled) return

      const { uri, type } = result
      const fileInfo = await getFileInfo(result.uri)

      if (!fileInfo?.size) {
        alert("Can't select this file as the size is unknown.")
        return
      }

      if (type === 'image') {
        const isLt15MB = isLessThanTheMB(fileInfo.size, 15)
        if (!isLt15MB) {
          alert(`Image size must be smaller than 15MB!`)
          return
        }
      }

      if (type === 'video') {
        const isLt500MB = isLessThanTheMB(fileInfo.size, 500)
        if (!isLt500MB) {
          alert(`Video size must be smaller than 500MB!`)
          return
        }
      }

      // Save or process with the result.uri
    } catch (error) {
      console.info(error)
    }
 }
Run Code Online (Sandbox Code Playgroud)