Flutter中生成Image转XFile时遭遇文件不存在错误(errno=2)
解决XFile路径不存在的错误
问题原因
你只通过XFile(path, bytes: img!.getBytes())创建了XFile对象,但并没有把图片字节实际写入到指定路径的文件中,磁盘上根本不存在这个文件,所以FileImage(File(imageFile!.path))会报找不到文件的错误。
解决方案
必须先将处理后的图片字节写入到目标路径的文件,再用该路径创建XFile。
修改后的完整代码
final XFile? pickedImage = await ImagePicker().pickImage(source: source); if (pickedImage != null) { // 转灰度处理 final Uint8List imgBytes = await File(pickedImage.path).readAsBytes(); final imgLib.Image? image = imgLib.decodeImage(imgBytes); final imgLib.Image grayImage = imgLib.grayscale(image!); final root = await getTemporaryDirectory(); final path = "${root.path}/a.png"; // 核心步骤:将处理后的图片写入磁盘文件 final File outputFile = File(path); await outputFile.writeAsBytes(imgLib.encodePng(grayImage)); // 基于已存在的文件创建XFile imageFile = XFile(path); }
UI代码无需改动
image: FileImage(File(imageFile!.path)),
内容的提问来源于stack exchange,提问作者Soton Ahmed
相关产品推荐
相关产品推荐

