skip to Main Content

I’m using the following code to select and load an image. Is there any way to validate if the image returned is valid? For example, users pick up video files instead of image files in which case an exception should be raised.The issue is that the Exception block never gets called even if the return image is invalid.

  Future<Image?> imgFromGallery(
          double cWidth, double cHeight ) async {
        final picker = ImagePicker();
        final XFile? pickedImage = await picker.pickImage(
            source: ImageSource.gallery,
            maxWidth: cHeight,
            maxHeight: cHeight,
            imageQuality: 100);
    
        if (pickedImage == null)  return Future.value();
    
        try {
          Image? img = Image.file(File(pickedImage.path));
         
          if (img == null) //this won't work, always false
 return Future.value();
          
          return img;
        } catch (e) {

return null; //this will never get called
print(e);
}

        return Future.value();
      } 

2

Answers


  1. You can also check if image file exists by simply reading it as a file and check its existence using image.isNotEmpty.

    Future<Image?> imgFromGallery(double cWidth, double cHeight) async {
      final picker = ImagePicker();
      final XFile? pickedImage = await picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: cHeight,
        maxHeight: cHeight,
        imageQuality: 100,
      );
      if (pickedImage == null) return null;
      try {
        final file = File(pickedImage.path);
        final image = await file.readAsBytes();
        // Perform image validation
        if (image.isNotEmpty) {
          final img = Image.memory(image);
          return img;
        } else {
          // Invalid image file
          return null;
        }
      } catch (e) {
        print(e);
      }
    
      return null;
    }
    
    Login or Signup to reply.
  2. Here is way you can limiting your pickup type.

    final ImagePicker picker = ImagePicker();
    // Pick an image.
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    // Capture a photo.
    final XFile? photo = await picker.pickImage(source: ImageSource.camera);
    // Pick a video.
    final XFile? galleryVideo =
        await picker.pickVideo(source: ImageSource.gallery);
    // Capture a video.
    final XFile? cameraVideo = await picker.pickVideo(source: ImageSource.camera);
    // Pick multiple images.
    final List<XFile> images = await picker.pickMultiImage();
    

    For more refer library document.-> https://pub.dev/packages/image_picker

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search