如何在Sqlite中将图像存储为blob&如何检索它?

我想将一个图像(来自url)存储到sqlite数据库中

为此,我使用:

db=新数据库(getApplicationContext());
URL=新URL(“http://sree.cc/wp-content/uploads/schogini_team.png");
URLConnection ucon=url.openConnection();
InputStream=ucon.getInputStream();
BufferedInputStream bis=新的BufferedInputStream(is,128);
ByteArrayBuffer倒钩=新ByteArrayBuffer(128);
int电流=0;
而((当前=bis.read())!=-1){
倒钩追加((字节)当前值);
}
ContentValues filedata=新ContentValues();
put(DataBase.IMG_SRC,barb.toByteArray());
db.insert(DataBase.Table_Img,null,filedata);

插入()中:

公共void insert(字符串tableImg、对象、,
ContentValues(dataToInsert){
//TODO自动生成的方法存根
字符串sql=“插入到“+tableImg+”(“+ID+”,“+IMG_SRC+”)中”+
“值(“+1+”、“+dataToInsert+”)”;
execSQL(sql);
}

对于图像检索:

Cursor Cursor=db.选择datatoshow(DataBase.Table\u Img,DataBase.Img\u SRC);
字节[]imageByteArray=cursor.getBlob(cursor.getColumnIndex(DataBase.IMG_SRC));
cursor.close();
ByteArrayInputStream imageStream=新的ByteArrayInputStream(imageByteArray);
位图theImage=BitmapFactory.decodeStream(图像流);
系统输出打印项次(“>>>>>>>>>>>>>>>”+图像);

所以这里我得到了null

在我的数据库中,图像的值存储为:image=[[email protected]]

这里是我用于我的应用程序的代码

此代码将从url获取一个图像,并将其转换为字节数组

字节[]logoImage=getLogoImage(IMAGEURL);
私有字节[]getLogoImage(字符串url){
试一试{
URL imageUrl=新URL(URL);
URLConnection ucon=imageUrl.openConnection();
InputStream=ucon.getInputStream();
BufferedInputStream bis=新的BufferedInputStream(is);
ByteArrayBuffer baf=新ByteArrayBuffer(500);
int电流=0;
而((当前=bis.read())!=-1){
baf.append((字节)当前值);
}
返回baf.toByteArray();
}捕获(例外e){
Log.d(“ImageManager”,“错误:+e.toString());
}
返回null;
}

为了将图像保存到db,我使用了以下代码

公共作废插入器(){
SQLiteDatabase db=dbHelper.getWritableDatabase();
String delSql=“从帐户中删除”;
SQLiteStatement delStmt=db.compileStatement(delSql);
delStmt.execute();
String sql=“插入帐户(帐户id、帐户名称、帐户图像)值(?,?)”;
SQLiteStatement insertStmt=db.compileStatement(sql);
insertStmt.clearBindings();
insertStmt.bindString(1,Integer.toString(this.accId));
insertStmt.bindString(2,this.accName);
insertStmt.bindBlob(3,this.accImage);
insertStmt.executeInsert();
db.close();
}

要检索回图像,这是我使用的代码

公共帐户getCurrentAccount(){
SQLiteDatabase db=dbHelper.getWritableDatabase();
String sql=“从帐户中选择*”;
Cursor Cursor=db.rawQuery(sql,新字符串[]{});
if(cursor.moveToFirst()){
this.accId=cursor.getInt(0);
this.accName=cursor.getString(1);
this.accImage=cursor.getBlob(2);
}
if(cursor!=null&!cursor.isClosed()){
cursor.close();
}
db.close();
if(cursor.getCount()==0){
返回null;
}否则{
归还这个;
}
}

最后,将此图像加载到imageview

logoImage.setImageBitmap(BitmapFactory.decodeByteArray(currentAccount.accImage、,
0,currentAccount.accImage.length);

发表评论