該代碼會從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;
}
將圖像保存到數據庫我使用此代碼。
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));
好。可能是這個問題。但我不知道該怎麼做。任何鏈接/示例代碼都會有幫助。它甚至會因設備而異?它如何發現?謝謝。 – redGREENblue 2011-03-12 12:54:43
http://www.coderanch.com/t/449045/Android/Mobile/byte-image上有一個鏈接,它使用流而不是緩衝區來獲取字節數組。這可能是最簡單的方法。 – 2011-03-12 13:12:45
謝謝。將通過這一點。 – redGREENblue 2011-03-12 13:17:23