2017-10-12 27 views
0

我正在創建一個應用程序,我希望能夠在不卸載應用程序的情況下稍後更改圖像。 由於我們不能寫入可繪製的文件夾,我想我使用數據庫來保存圖像,我可以在稍後操作數據。如何將圖像從url添加到Android的Sqlite數據庫並基於索引檢索

我測試了一些代碼,但它似乎沒有工作。我可以從網址中拉出圖片並顯示。但我還沒有能夠弄清楚如何把圖像從網址上的數據庫。

看看我的代碼。

public class MainActivity extends AppCompatActivity { 
Intent intent; 
Button btn; 
DataBaseHandler db; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    if (android.os.Build.VERSION.SDK_INT > 9) { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
    } 

    btn = (Button)findViewById(R.id.btn); 
    final ImageView img = (ImageView)findViewById(R.id.img); 
    //initialize db 
    db = new DataBaseHandler(this); 


    URL url = null; 
    try { 
     url = new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQSh3goeAXlletPgkm3pm1F4DgxwArOKS9STyK02ocNn0AZ6Q9u"); 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } 
    try { 
     url = new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQSh3goeAXlletPgkm3pm1F4DgxwArOKS9STyK02ocNn0AZ6Q9u"); 
     final Bitmap image = BitmapFactory.decodeStream(url.openStream()); 
     byte[]inpudata = Utils.getImageBytes(image); 
     db.insertImage(inpudata); 
     btn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       byte[]inpudata = db.retreiveImageFromDB(); 


       img.setImageBitmap(Utils.getImage(inpudata)); 
      } 
     }); 
    } catch(IOException e) { 
     System.out.println(e); 
    } 




} 



} 

而且數據庫Helper類

public class DataBaseHandler{ 

public static final String IMAGE_ID = "id"; 
public static final String IMAGE = "image"; 
private final Context mContext; 

private DatabaseHelper mDbHelper; 
private SQLiteDatabase mDb; 

private static final String DATABASE_NAME = "Images.db"; 
private static final int DATABASE_VERSION = 1; 

private static final String IMAGES_TABLE = "ImagesTable"; 

private static final String CREATE_IMAGES_TABLE = 
     "CREATE TABLE " + IMAGES_TABLE + " (" + 
       IMAGE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
       + IMAGE + " BLOB NOT NULL);"; 


private static class DatabaseHelper extends SQLiteOpenHelper { 
    DatabaseHelper(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 

    public void onCreate(SQLiteDatabase db) { 
     db.execSQL(CREATE_IMAGES_TABLE); 
    } 

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     db.execSQL("DROP TABLE IF EXISTS " + CREATE_IMAGES_TABLE); 
     onCreate(db); 
    } 
} 

public void Reset() { 
    mDbHelper.onUpgrade(this.mDb, 1, 1); 
} 

public DataBaseHandler(Context ctx) { 
    mContext = ctx; 
    mDbHelper = new DatabaseHelper(mContext); 
} 

public DataBaseHandler open() throws SQLException { 
    mDb = mDbHelper.getWritableDatabase(); 
    return this; 
} 

public void close() { 
    mDbHelper.close(); 
} 

// Insert the image to the Sqlite DB 
public void insertImage(byte[] imageBytes) { 
    ContentValues cv = new ContentValues(); 
    cv.put(IMAGE, imageBytes); 
    mDb.insert(IMAGES_TABLE, null, cv); 
} 

// Get the image from SQLite DB 
// We will just get the last image we just saved for convenience... 
public byte[] retreiveImageFromDB() { 
    Cursor cur = mDb.query(true, IMAGES_TABLE, new String[]{IMAGE,}, 
      null, null, null, null, 
      IMAGE_ID + " DESC", "1"); 
    if (cur.moveToFirst()) { 
     byte[] blob = cur.getBlob(cur.getColumnIndex(IMAGE)); 
     cur.close(); 
     return blob; 
    } 
    cur.close(); 
    return null; 
} 
} 
+0

您是否檢查過https://stackoverflow.com/questions/9357668/how-to-store-image-in-sqlite-database? – Isuru

+0

請改變主意:在本地保存圖像,並且**不要用BLOBS臃腫數據庫**。只存儲圖像路徑。 –

+0

或者,更好的是,甚至不需要保存圖像。只需存儲網址。 –

回答

1

它來存儲圖像的本地數據庫中,因爲有光標大小的限制不是好主意See details 你可以做一些像服務器這樣 先下載圖像並存儲在內部存儲器中,然後將本地路徑存儲在數據庫中

private String saveToInternalStorage(Bitmap bitmapImage){ 
     ContextWrapper cw = new ContextWrapper(getApplicationContext()); 
     // path to /data/data/yourapp/app_data/imageDir 
     File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); 
     // Create imageDir 
     File mypath=new File(directory,"profile.jpg"); 

     FileOutputStream fos = null; 
     try {   
      fos = new FileOutputStream(mypath); 
     // Use the compress method on the BitMap object to write image to the OutputStream 
      bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos); 
     } catch (Exception e) { 
       e.printStackTrace(); 
     } finally { 
      try { 
       fos.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return directory.getAbsolutePath(); 
    } 

使用從https://stackoverflow.com/a/17674787/2941375

0

private void loadImageFromStorage(String path) 
{ 

    try { 
     File f=new File(path, "profile.jpg"); 
     Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f)); 
      ImageView img=(ImageView)findViewById(R.id.imgPicker); 
     img.setImageBitmap(b); 
    } 
    catch (FileNotFoundException e) 
    { 
     e.printStackTrace(); 
    } 

} 

參考,當你每次都轉換爲字節,反之亦然時間存儲在數據庫中的圖像。它也可能導致內存異常,所以我會建議你,而不是在數據庫中存儲圖像嘗試將該圖像的URL存儲在數據庫中,然後從DB獲取圖像的URL並使用Picasso或Glide圖像庫顯示圖像。

+0

我欣賞,但我不是在通過互聯網直播圖像。考慮到應用程序在某個時候自動下載圖像,保存並脫機使用。 – imohchard

相關問題