如何保存用户使用ImagePicker拾取的hive DB中的图像?

92vpleto  于 2023-10-18  发布在  Hive
关注(0)|答案(1)|浏览(217)

当我实现我自己的方式把图像在Hive,但它没有工作。我在网上搜索,但没有找到任何合理的解决方案。一个完整的代码来实现它可能是有帮助的。任何帮助将不胜感激。谢谢你,谢谢
我用来挑选图像并将其放入Hive的代码。

  1. File? _image;
  2. Future getAndSaveImage() async {
  3. final image = await ImagePicker().pickImage(source: ImageSource.gallery);
  4. if (image == null) return;
  5. final tempImage = File(image.path);
  6. setState(() {
  7. _image = tempImage;
  8. images.put(_nameController.text, ProfileImage(_image!));
  9. });
  10. }

配置单元模型类

  1. import 'dart:io';
  2. import 'package:hive/hive.dart';
  3. part 'profile_image.g.dart';
  4. @HiveType(typeId: 2)
  5. class ProfileImage {
  6. ProfileImage(this.profileStudentImage);
  7. @HiveField(0)
  8. final File profileStudentImage;
  9. }

请给予一个适当的工作解决方案,我真的需要它。😢

8i9zcol2

8i9zcol21#

您首先需要将图像转换为可以存储在Hive中的格式,通常是Uint8List(字节数组)。然后,您可以将此字节数组保存到Hive框中
在将图像保存到Hive之前,您需要将其转换为Uint8List。您可以使用ImagePicker包选择图像并将其转换为字节。

  1. PickedFile pickedFile = await ImagePicker().getImage(source: ImageSource.gallery);
  2. List<int> imageBytes = await pickedFile.readAsBytes();
  3. Uint8List imageUint8List = Uint8List.fromList(imageBytes);

保存图像到配置单元:
一旦你有了Uint8List格式的图像,你可以保存它到Hive:

  1. Box imageBox = Hive.box('images'); // Open the 'images' box
  2. // Save the Uint8List to Hive
  3. imageBox.put('image_key', imageUint8List);

图片来自Hive:

  1. Box imageBox = Hive.box('images'); // Open the 'images' box
  2. // Get the Uint8List from Hive
  3. Uint8List retrievedImage = imageBox.get('image_key');

显示图像:

  1. Image.memory(retrievedImage);
展开查看全部

相关问题