在Flutter中如何设置图像选择器中图像的最大尺寸?

huangapple go评论91阅读模式
英文:

How to set maximum size of image from image Picker in Flutter

问题

这是我的代码

chooseImage() async {
    XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.gallery,
    );
    imagePath = await pickedFile!.readAsBytes();  
}
英文:

this is my code

chooseImage() async {
    XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.gallery,
    );
    imagePath = await pickedFile!.readAsBytes();  
}

答案1

得分: 2

如果您想完全阻止超过特定大小的文件,您可以使用其长度属性来检查文件的大小,并相应处理结果。

chooseImage() async {
    var maxFileSizeInBytes = 2 * 1048576; // 2MB(您可能希望将此值放在函数外部,以便在其他地方重复使用)

    XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.gallery,
    );
    var imagePath = await pickedFile!.readAsBytes();

    var fileSize = imagePath.length; // 获取文件大小(字节)
    if (fileSize <= maxFileSizeInBytes) {
        // 文件大小合适,上传/使用它
    } else {
        // 文件太大,要求用户上传较小的文件,或者压缩文件/图像
    }
}
英文:

If you want to completely block files over a certain size, you can check the size of the file using it's length property, and handle the result accordingly

chooseImage() async {
    var maxFileSizeInBytes = 2 * 1048576; // 2MB (You&#39;ll probably want this outside of this function so you can reuse the value elsewhere)

    XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.gallery,
    );
    var imagePath = await pickedFile!.readAsBytes();

    var fileSize = imagePath.length; // Get the file size in bytes
    if (fileSize &lt;= maxFileSizeInBytes) {
        // File is the right size, upload/use it
    } else {
        // File is too large, ask user to upload a smaller file, or compress the file/image
    }
}

答案2

得分: 1

你可以使用 imageQuality 属性。质量越高,图像文件大小越大。

chooseImage() async {
  XFile? pickedFile = await ImagePicker().pickImage(
    source: ImageSource.gallery,
    imageQuality: 50, // 将质量设置为 50%
  );
  imagePath = await pickedFile!.readAsBytes();  
}
英文:

You can use imageQuality properties. The higher the quality, the larger the file size of the image.

chooseImage() async {
  XFile? pickedFile = await ImagePicker().pickImage(
    source: ImageSource.gallery,
    imageQuality: 50, // Set the quality to 50%
  );
  imagePath = await pickedFile!.readAsBytes();  
}

huangapple
  • 本文由 发表于 2023年4月13日 16:05:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76003075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定