如何将图像转换为字节并在颤动中再次将其转换为图像?
how to convert image to byte and again convert it to image in flutter?
我正在尝试使用 image_picker 插件。我可以使用此插件将图像作为文件获取。我需要将此图像转换为字节并发送到 api。所以我尝试使用 dart:convert 将图像转换为字节字符串。现在,当我解码时,我得到一个 Uint8List 类型。如何将其转换为文件并显示在 Image.file() 中。我无法从这里继续。谁能帮我解决这个问题。
考虑一下我正在从 api 响应中获取 decodedBytes,如何将它们转换为显示在图像小部件中
这是我到目前为止尝试过的代码。
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
imageURI = image;
final bytes = image.readAsBytesSync();
String img64 = base64Encode(bytes);
print(bytes);
print(img64);
final decodedBytes = base64Decode(img64);
print(decodedBytes);
//consider i am getting this decodedBytes i am getting from a api response, how can i convert them to display in a Image widget
});
我在使用 writeAsBytesSync()、
时收到此错误
Unhandled Exception: FileSystemException: Cannot open file, path = 'decodedimg.png'
您收到此错误,因为您无法写入应用程序沙箱中的任意位置。您可以使用 path_provider 查找临时目录。
但在您的情况下,只需使用 image
对象,pickImage
已经 returns 一个文件对象,因此只需使用 Image.file(image)
如果你想将 base64 解码到一个临时目录中,你可以使用:
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
Future<File> writeImageTemp(String base64Image, String imageName) async {
final dir = await getTemporaryDirectory();
await dir.create(recursive: true);
final tempFile = File(path.join(dir.path, imageName));
await tempFile.writeAsBytes(base64.decode(base64Image));
return tempFile;
}
与 pubspec.yaml:
dependencies:
path: ^1.6.0
path_provider: ^1.6.7
我正在尝试使用 image_picker 插件。我可以使用此插件将图像作为文件获取。我需要将此图像转换为字节并发送到 api。所以我尝试使用 dart:convert 将图像转换为字节字符串。现在,当我解码时,我得到一个 Uint8List 类型。如何将其转换为文件并显示在 Image.file() 中。我无法从这里继续。谁能帮我解决这个问题。
考虑一下我正在从 api 响应中获取 decodedBytes,如何将它们转换为显示在图像小部件中
这是我到目前为止尝试过的代码。
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
imageURI = image;
final bytes = image.readAsBytesSync();
String img64 = base64Encode(bytes);
print(bytes);
print(img64);
final decodedBytes = base64Decode(img64);
print(decodedBytes);
//consider i am getting this decodedBytes i am getting from a api response, how can i convert them to display in a Image widget
});
我在使用 writeAsBytesSync()、
时收到此错误Unhandled Exception: FileSystemException: Cannot open file, path = 'decodedimg.png'
您收到此错误,因为您无法写入应用程序沙箱中的任意位置。您可以使用 path_provider 查找临时目录。
但在您的情况下,只需使用 image
对象,pickImage
已经 returns 一个文件对象,因此只需使用 Image.file(image)
如果你想将 base64 解码到一个临时目录中,你可以使用:
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
Future<File> writeImageTemp(String base64Image, String imageName) async {
final dir = await getTemporaryDirectory();
await dir.create(recursive: true);
final tempFile = File(path.join(dir.path, imageName));
await tempFile.writeAsBytes(base64.decode(base64Image));
return tempFile;
}
与 pubspec.yaml:
dependencies:
path: ^1.6.0
path_provider: ^1.6.7