Android 如何在Sqlite中将图像存储为blob&;如何检索它?
我想将一个图像(来自url)存储到sqlite数据库中 为此,我使用:Android 如何在Sqlite中将图像存储为blob&;如何检索它?,android,image,blob,Android,Image,Blob,我想将一个图像(来自url)存储到sqlite数据库中 为此,我使用: db = new DataBase(getApplicationContext()); URL url = new URL("http://sree.cc/wp-content/uploads/schogini_team.png"); URLConnection ucon = url.openConnection(); InputStream is = ucon.getInputStream(); BufferedInput
db = new DataBase(getApplicationContext());
URL url = new URL("http://sree.cc/wp-content/uploads/schogini_team.png");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is,128);
ByteArrayBuffer barb= new ByteArrayBuffer(128);
int current = 0;
while ((current = bis.read()) != -1) {
barb.append((byte) current);
}
ContentValues filedata= new ContentValues();
filedata.put(DataBase.IMG_SRC,barb.toByteArray());
db.insert(DataBase.Table_Img, null, filedata);
在插入()
中:
对于图像检索:
Cursor cursor = db.selectDataToShow(DataBase.Table_Img, DataBase.IMG_SRC);
byte[] imageByteArray=cursor.getBlob(cursor.getColumnIndex(DataBase.IMG_SRC));
cursor.close();
ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByteArray);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
System.out.println(">>>>>>>>>>>>>>>>>>>>>> "+theImage);
所以这里我得到了null
在我的数据库中,图像的值存储为:image=[B@43e5ac48]
插入()
希望它能帮助您。这里是我用于我的应用程序的代码 此代码将从url获取一个图像,并将其转换为字节数组
byte[] logoImage = getLogoImage(IMAGEURL);
private byte[] getLogoImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
为了将图像保存到db,我使用了以下代码
public void insertUser(){
SQLiteDatabase db = dbHelper.getWritableDatabase();
String delSql = "DELETE FROM ACCOUNTS";
SQLiteStatement delStmt = db.compileStatement(delSql);
delStmt.execute();
String sql = "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)";
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();
}
要检索回图像,这是我使用的代码
public Account getCurrentAccount() {
SQLiteDatabase db = dbHelper.getWritableDatabase();
String sql = "SELECT * FROM ACCOUNTS";
Cursor cursor = db.rawQuery(sql, new String[] {});
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){
return null;
} else {
return this;
}
}
最后,将此图像加载到imageview
logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage,
0,currentAccount.accImage.length));
在DBAdaper即database helper类中,如下声明表
private static final String USERDETAILS=
"create table userdetails(usersno integer primary key autoincrement,userid text not null ,username text not null,password text not null,photo BLOB,visibility text not null);";
像这样插入值
首先将图像转换为字节[]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.common)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] photo = baos.toByteArray();
db.insertUserDetails(value1,value2, value3, photo,value2);
无纸课堂
public long insertUserDetails(String uname,String userid, String pass, byte[] photo,String visibility)
{
ContentValues initialValues = new ContentValues();
initialValues.put("username", uname);
initialValues.put("userid",userid);
initialValues.put("password", pass);
initialValues.put("photo",photo);
initialValues.put("visibility",visibility);
return db.insert("userdetails", null, initialValues);
}
按如下方式检索图像
Cursor cur=your query;
while(cur.moveToNext())
{
byte[] photo=cur.getBlob(index of blob cloumn);
}
将字节[]转换为图像
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);
我认为此内容可能会解决您的问题您可能还希望对base64进行编码和解码
function uncompress(str:String):ByteArray {
import mx.utils.Base64Decoder;
var dec:Base64Decoder = new Base64Decoder();
dec.decode(str);
var newByteArr:ByteArray=dec.toByteArray();
return newByteArr;
}
// Compress a ByteArray into a Base64 String.
function compress(bytes:ByteArray):String {
import mx.utils.Base64Decoder; //Transform String in a ByteArray.
import mx.utils.Base64Encoder; //Transform ByteArray in a readable string.
var enc:Base64Encoder = new Base64Encoder();
enc.encodeBytes(bytes);
return enc.drain().split("\n").join("");
}
为了一个离子工程
var imgURI = "";
var imgBBDD = ""; //sqllite for save into
function takepicture() {
var options = {
quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
targetHeight: 300,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imageData) {
imgURI = "data:image/jpeg;base64," + imageData;
imgBBDD = imageData;
}, function(err) {
// An error occured. Show a message to the user
});
}
var imgURI=“”;
var imgBBDD=“”//用于保存到的sqllite
函数takepicture(){
变量选项={
质量:75,
destinationType:Camera.destinationType.DATA\u URL,
源类型:Camera.PictureSourceType.Camera,
允许:是的,
编码类型:Camera.encodingType.JPEG,
目标宽度:300,
目标:300,
popoverOptions:CamerapoverOptions,
saveToPhotoAlbum:false
};
$cordovaCamera.getPicture(选项)。然后(函数(imageData){
imgURI=“数据:图像/jpeg;base64,”+imageData;
imgBBDD=图像数据;
},函数(err){
//发生错误。向用户显示消息
});
}
现在我们将imgBBDD放入SqlLite中
function saveImage = function (theId, theimage){
var insertQuery = "INSERT INTO images(id, image) VALUES("+theId+", '"+theimage+"');"
console.log('>>>>>>>');
DDBB.SelectQuery(insertQuery)
.then( function(result) {
console.log("Image saved");
})
.catch( function(err)
{
deferred.resolve(err);
return cb(err);
});
}
函数saveImage=函数(theId,theimage){
var insertQuery=“插入图像(id,图像)值(“+theId+”,“+theimage+”)
console.log('>>>>>');
DDBB.SelectQuery(插入查询)
.然后(函数(结果){
console.log(“已保存图像”);
})
.catch(函数(err)
{
延迟。解决(错误);
返回cb(错误);
});
}
服务器端(php)
$request=文件\u获取\u内容(“php://input"); // 获取原始数据
$dades=json_decode($request,true);//返回为数组时为true
如果($dades==“”){
$array=array();
$array['error']=-1;
$array['descError']=“获取文件时出错”;
$array['logError']='';
echo json_编码($array);
出口
}
//再次将图像发送到客户端
标题(“内容类型:图像/jpeg”);
回声';
首先使用imageByteArray.length变量检查字节[]长度,即photo.length,检查是否从游标检索到字节[]。如果该值大于零,那么您肯定会得到正确的位图。如果长度为零,则检查您的查询。“System.out.println(“>>>>>>>>>>>>>”+imageByteArray.length);“它打印的内容是什么
bitmap.compress(bitmap.CompressFormat.PNG,100,baos)代码>??那我不想压缩我的图像呢?在这里找到我的答案insertStmt.bindBlob(3,this.accImage);用于插入图像,其中accImage是从第一个代码块中的getLogoImage方法返回的字节数组。我在位图处得到null。我得到了byte[]的值。在将url转换为字节数组后,是否可以将字节数组设置为图像视图。如果您能够查看图像,那么。然后我们就可以知道数据库操作中发生了一些问题。否则,您从服务器访问映像的方式可能会出错。@blessenm我正在这样做。但是在sqlite中有更多的图片/字节数组..如何避免位图内存不足错误?光标null检查毫无意义:您已经在moveToFirst调用中使用了它。在获取db时,我得到的不完全是字节[]。。。。。有什么帮助吗?当您可以存储字节数组时,没有理由使用base64,因为这只会增加所需的存储空间(并浪费不必要的编码时间)。Base64编码几乎不可读。
var imgURI = "";
var imgBBDD = ""; //sqllite for save into
function takepicture() {
var options = {
quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
targetHeight: 300,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imageData) {
imgURI = "data:image/jpeg;base64," + imageData;
imgBBDD = imageData;
}, function(err) {
// An error occured. Show a message to the user
});
}
function saveImage = function (theId, theimage){
var insertQuery = "INSERT INTO images(id, image) VALUES("+theId+", '"+theimage+"');"
console.log('>>>>>>>');
DDBB.SelectQuery(insertQuery)
.then( function(result) {
console.log("Image saved");
})
.catch( function(err)
{
deferred.resolve(err);
return cb(err);
});
}
$request = file_get_contents("php://input"); // gets the raw data
$dades = json_decode($request,true); // true for return as array
if($dades==""){
$array = array();
$array['error'] = -1;
$array['descError'] = "Error when get the file";
$array['logError'] = '';
echo json_encode($array);
exit;
}
//send the image again to the client
header('Content-Type: image/jpeg');
echo '';
byte[] byteArray = rs.getBytes("columnname");
Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length);