Shadeeka Nimesh
Shadeeka Nimesh

Reputation: 944

How to retreive image data in sqlite database in flutter?

I want to retrieve image data in sqlite. im using below code

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

i want to take image and after save it sqlite.if can get and set image from sqlite database ?.

Upvotes: 4

Views: 9372

Answers (3)

karmelcorn
karmelcorn

Reputation: 597

You can also save the image as a BLOB (data type: UInt8List). Storing both as Blob (UInt8List) or String(with Base64encoder) in sqflite works. The key was to use MemoryImage instead of Image.memory. Otherwise you would get type 'Image' is not a subtype of type 'ImageProvider ' error.

//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],
      ),
   ]);

Upvotes: 0

Shadeeka Nimesh
Shadeeka Nimesh

Reputation: 944

I found the solution in my question. I'm getting the image from an image_picker and Encode it to BASE64 string value like below

 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;

      });
}

after creating an SQLite database dbhelper.dart file to retrieve String values and database model file Image.dart for the get and set the String values.

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;
  }
}

last getting String value from the database and Decode String value to the Image file.

Getting image from database

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

                 return images;
            }

after Decode string value to the Image file

    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)
                     ),
                    );
                   }
                 );
                }
              }
           ), 

i think that is helpful for other flutter,sqlite developers

Upvotes: 6

Kenneth Li
Kenneth Li

Reputation: 1742

import 'dart:convert';

import 'dart:typed_data';



    Uint8List bytesImage1;

    bool bolWithImage1 = false;

    try {

      bytesImage1 =

          base64Decode(base64StringFromSql);

      bolWithImage1 = true;

    } catch (err) {}

i.e. if bolWithImage1 is true, the conversion is successful. You can then use image.memory(byteImage1, ......) to show the image in flutter.

Upvotes: 0

Related Questions