flutter 在抖动中拾取/选择图像时,如何验证图像大小?

3xiyfsfu  于 2023-01-27  发布在  Flutter
关注(0)|答案(1)|浏览(164)

下面是从画廊获取图像的代码。

Future getImage() async {
    var image = await ImagePicker().getImage(source: ImageSource.gallery);
     getImageSize();
    // imageQuality: 50;
    setState(() {
      selectedImage = File(image!.path);
    });
  }

获取所选图像大小的代码。

double getImageSize(File selectedImage) {
    final bytes = selectedImage.readAsBytesSync().lengthInBytes;
    final kb = bytes / 1024;
    final mb = kb / 1024;
    if (kb < 5000.0) {
      print("Image is Less than 5MB");
    } else {
      print("Image is More than 5MB...!!!");
    }
    return kb;
  }

因此,在选择图像并检查图像是否小于5mb后,应返回“kb”,如果图像大小大于“5mb”,则函数应在SnackBar中显示错误消息。

wydwbb8l

wydwbb8l1#

你可以这样做

XFile? imageFile = await ImagePicker().pickImage(source: ImageSource.camera);
 if (imageFile != null) {
      final decodedImage = await decodeImageFromList(await imageFile.readAsBytes());
    if (decodedImage.height > 255 && decodedImage.width > 255) {
        //do your validation here 
         }
  }

相关问题