【问题标题】:Convert Image to XFile in Flutter在 Flutter 中将图像转换为 XFile
【发布时间】:2022-12-12 21:37:52
【问题描述】:
无法打开文件,路径 = '/data/data/com.example.demo/cache/a.png'(操作系统错误:没有这样的文件或目录,errno = 2)
我想将生成的图像转换为 XFile。当我尝试时,我遇到了这个问题(无法打开文件,路径 = '/data/data/com.example.demo/cache/a.png'(操作系统错误:没有这样的文件或目录,errno = 2))。
函数内代码:
final XFile? pickedImage = await ImagePicker().pickImage(source: source);
if (pickedImage != null) {
//for convert greyscale
final Uint8List imgBytes = await File(pickedImage.path).readAsBytes();
final imgLib.Image? image = imgLib.decodeImage(imgBytes);
img = imgLib.grayscale(image!);
print("object img: ${img!.getBytes()}");
final root = await getTemporaryDirectory();
final path = "${root.path}/a.png";
print("object path: $path");
imageFile = XFile(path,bytes: img!.getBytes());
和用户界面代码:
image: FileImage(File(imageFile!.path)),
【问题讨论】:
标签:
android
ios
flutter
dart
【解决方案1】:
您遇到此错误是因为应用程序不会在整个文件管理器中进行搜索以在不同设备上获取此图像。所以将 base64 字符串存储在一个变量中,你也可以对其进行解码。顺便说一句,我尽力以各种方式回答你的问题
我看到了你的代码,我认为你也在将它转换成字节和 base64。你可以使用下面的代码。它将从图库中选择图像,然后将其存储为 Xfile,然后读取它的字节并将字节转换为 base 64 字符串
//Variables
ImagePicker picker = ImagePicker();
XFile? image;
File? f = null;
//picking image from gallery
InkWell(
onTap: () async {
image = await picker.pickImage(source: ImageSource.gallery);
setState(() {
f = File(image!.path);});
},
child: Center(
child: f == null?
Image.asset('assets/images/placeholder.png',
width: 194, height: 174)
: ClipRRect( borderRadius:BorderRadius.all(
Radius.circular(10),),
child: Image.file(f!, width: 194,height:174,
fit: BoxFit.cover,)),
),
),
//converting now to xfile => byte => base64
if (f != null) {
const FlutterSecureStorage storage =
FlutterSecureStorage();
setState(() {
APIcalling = true;
});
final bytes = f!.readAsBytesSync();
List<int> imageBytes =
await image!.readAsBytes();
final String b64 =
base64Encode(imageBytes);
log(b64);