如何在flutter中检索sqlite数据库中的图像数据?

时间:2019-04-04 04:28:53

标签: image sqlite flutter camera

我想用sqlite检索图像数据。我正在使用下面的代码

var image = await ImagePicker.pickImage(source: imageSource);
List<int> bytes = await image.readAsBytes();

我要拍摄图像,然后将其保存为sqlite.if是否可以从sqlite数据库中获取并设置图像?。

3 个答案:

答案 0 :(得分:1)

我在问题中找到了解决方案。 我从image_picker获取图像并将其编码为BASE64字符串值,如下所示:

 Uint8List _bytesImage;   
 File _image;
 String  base64Image;

Future getImage() async {
     var image2 = await ImagePicker.pickImage(
      source: ImageSource.gallery,

      );
    List<int> imageBytes = image2.readAsBytesSync();
    print(imageBytes);
    base64Image = base64Encode(imageBytes);
    print('string is');
    print(base64Image);
    print("You selected gallery image : " + image2.path);

    _bytesImage = Base64Decoder().convert(base64Image);

    setState(() {

      _image=image2;

      });
}

在创建SQLite数据库dbhelper.dart文件以获取字符串值和数据库模型文件Image.dart以获取并设置字符串值之后。

  

image.dart

class Image{

  int id;
  String image;


  Employee(this.id, this.image);

   Employee.fromMap(Map map) {
    id= map[id];
    image = map[image];

  }

}
  

dbhelper.dart

 class DBHelper {
  static Database _db;

  Future<Database> get db async {
    if (_db != null) return _db;
    _db = await initDb();
    return _db;
  }

  initDb() async {
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "test.db");
    var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
    return theDb;
  }

  void _onCreate(Database db, int version) async {
    // When creating the db, create the table
    await db.execute(
        "CREATE TABLE Imagedata(id INTEGER PRIMARY KEY, image TEXT)");
    print("Created tables");
  }

  void saveImage(Imagedata imagedata) async {
    var dbClient = await db;
    await dbClient.transaction((txn) async {
      return await txn.rawInsert(
          'INSERT INTO Imagedata(id, image) VALUES(' +
              '\'' +
              imagedata.id+
              '\'' +
              ',' +
              '\'' +
              imagedata.image +
              '\'' +
              ')');
    });
  }

  Future<List<Imagedata>> getMyImage() async {
    var dbClient = await db;
    List<Map> list = await dbClient.rawQuery('SELECT * FROM Imagedata');
    List<Imagedata> images= new List();
    for (int i = 0; i < list.length; i++) {
      images.add(new Imagedata(list[i]["id"], list[i]["image"]));
    }
    print(images.length);
    return images;
  }

   Future<int> deleteMyImage(Imagedata imagedata) async {
    var dbClient = await db;

    int res =
        await dbClient.rawDelete('DELETE * FROM Imagedata');
    return res;
  }
}

最后从数据库中获取String值,并将String值解码到Image文件。

从数据库获取图像

      Future<List<Employee>> fetchImageFromDatabase() async {
         var dbHelper = DBHelper();
         Future<List<Imagedata>> images= dbHelper.getImages();

                 return images;
            }

将字符串值解码为图像文件之后

    String DecoImage;
    Uint8List _bytesImage;

          FutureBuilder<List<Imagedata>>(
          future: fetchImageFromDatabase(),
          builder: (context, snapshot) {

             if (snapshot.hasData) {             
              return new
               ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {

                      DecoImage=snapshot.data[index].image;
                     _bytesImage = Base64Decoder().convert(DecoImage);

                    return new   SingleChildScrollView(
                      child:  Container(            
                   child: _bytesImage == null 
                      ? new Text('No image value.')
                      :  Image.memory(_bytesImage)
                     ),
                    );
                   }
                 );
                }
              }
           ), 

我认为这对其他flutter,sqlite开发人员很有帮助

答案 1 :(得分:0)

await doC

即如果bolWithImage1为true,则转换成功。然后,您可以使用image.memory(byteImage1,......)来显示图像。

答案 2 :(得分:0)

您还可以将图像另存为BLOB(数据类型:UInt8List)。在sqflite中将其存储为Blob(UInt8List)或String(使用Base64encoder)均可。关键是使用MemoryImage而不是Image.memory。否则,您将获得“ Image”类型不是“ ImageProvider”类型的子类型错误。

//First create column in database to store as BLOB.
await db.execute('CREATE TABLE $photoTable($colId INTEGER PRIMARY KEY AUTOINCREMENT, $colmage BLOB)');

//User imagePicker to get the image
File imageFile = await ImagePicker.pickImage(source: ImageSource.camera, maxHeight: 200, maxWidth: 200, imageQuality: 70);

//Get the file in UInt8List format
Uint8List imageInBytes = imageFile.readAsBytesSync();

//write the bytes to the database as a blob
db.rawUpdate('UPDATE $photoTable SET $colImage = ?, WHERE $colId =?', [imageInBytes, colID]);

//retrieve from database as a Blob of UInt8List 
var result = await db.query(photoTable, orderBy: '$colID ASC');
List<Photo> photoList = List<Photo>();

for (int i=0; i<result.length; i++){
  photoList.add(Photo.fromMapObject(userMapList[i]));
}

//Map function inside Photo object
Photo.fromMapObject(Map<String, dynamic> map) {
  this._id = map['id'];
  this._imageFile = map['image'];
}


//Display the image using using MemoryImage (returns ImagePicker Object) instead of Image.memory (returns an Image object). 
return Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
     CircleAvatar(
        backgroundImage:  MemoryImage(Photo.image),
        backgroundColor: Colors.blueGrey[50],
      ),
   ]);
相关问题