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

92vpleto  于 8个月前  发布在  Hive
关注(0)|答案(1)|浏览(57)

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

File? _image;
    Future getAndSaveImage() async {
      final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final tempImage = File(image.path);
setState(() {
  _image = tempImage;
  images.put(_nameController.text, ProfileImage(_image!));
});
    }

配置单元模型类

import 'dart:io';

import 'package:hive/hive.dart';

part 'profile_image.g.dart';

@HiveType(typeId: 2)
class ProfileImage {
  ProfileImage(this.profileStudentImage);
  @HiveField(0)
  final File profileStudentImage;
}

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

8i9zcol2

8i9zcol21#

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

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

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

Box imageBox = Hive.box('images'); // Open the 'images' box

// Save the Uint8List to Hive
imageBox.put('image_key', imageUint8List);

图片来自Hive:

Box imageBox = Hive.box('images'); // Open the 'images' box

// Get the Uint8List from Hive
Uint8List retrievedImage = imageBox.get('image_key');

显示图像:

Image.memory(retrievedImage);

相关问题