- Home /
How to save blob in bytes to sqlite
Hello! I'm a beginner with Unity. I'm having problem which I am trying to save a png to my database but the png needs to convert to bytes first.
// Use this for initialization
void Start () {
if (Application.platform != RuntimePlatform.Android) {
path = Application.dataPath + "/StreamingAssets/SqliteBlob.bytes";
} else {
path = Application.persistentDataPath + "/SqliteBlob.bytes";
if (!File.Exists (path)) {
WWW load = new WWW ("jar:file//" + Application.dataPath + "!/assets/" + "SqliteBlob.bytes");
while (!load.isDone) {
}
File.WriteAllBytes (path, load.bytes);
}
//opening connection
dbcon = new SqliteConnection ("URI = file:" + path);
dbcon.Open ();
// GetImageTexture ("SELECT blobContent FROM 'blobTable' WHERE id='" + id + "' ", out BlobTexture, out BlobWidth, out BlobHeight);
// GameObject.Find ("ContentImage").GetComponent<Image> ().sprite = Sprite.Create (BlobTexture, new Rect (0, 0, BlobWidth, BlobHeight), new Vector2 (0.5f, 0.5f));
}
}
// save image to blobtable db when the save_btn was click
public void click_ImageSave(){
Sprite blobR = Resources.Load("Images/white_black") as Sprite;
Texture2D blobtex = blobR.texture;
byte[] blobImage = blobtex.EncodeToPNG (); //returns bytes
SaveBlobData("blobTable", blobImage);
Debug.Log ("Successfully saved!");
}
public static bool SaveBlobData(String tableName, byte[] BlobContent) {
string query;
query = "INSERT INTO " + tableName + "(blobContent) VALUES (@BlobContent)";
try {
dbcmd = dbcon.CreateCommand();
dbcmd.CommandText = query;
SqliteParameter setParam = new SqliteParameter("@BlobContent", BlobContent);
setParam.Size = BlobContent.Length;
setParam.DbType = DbType.Binary;
dbcmd.Parameters.Add(setParam);
dbcmd.ExecuteNonQuery();
}
catch(Exception ex) {
Debug.LogError(ex.Message);
return false;
}
return true;
}
void GetImageTexture(string Query, out Texture2D tex, out int width, out int height) {
tex = new Texture2D (1024, 1024);
tex.LoadImage (GetBlobData (Query));
width = tex.width;
height = tex.height;
}
public static byte[] GetBlobData(string Query){
byte[] BlobContent = new byte[0];
dbcmd = dbcon.CreateCommand();
dbcmd.CommandText = Query;
reader = dbcmd.ExecuteReader();
while (reader.Read()) {
BlobContent = (byte[])reader["blob"];
}
return BlobContent;
}
Comment
Your answer
Follow this Question
Related Questions
Local sqlite data base with a unity webgl build in electron can’t access 0 Answers
Storing blob in SQLite 1 Answer
WebGL + Sqlite3 1 Answer
Array to blob 0 Answers
loading image as a blob from Sqlite,loading image from Sqlite 1 Answer