2

in my app I have set an image from the gallery in an image view. Now I want to store that image in my SQL database.

  1. What do I have to change in my SQL database? (BLOB??)
  2. What is the best way to retrieve the image from the image view and store it in the SQL Database?

Here is my SQL Database:

private static final String DATABASE_CREATE =
        "create table " + DATABASE_TABLE + " ("
                + KEY_ROWID + " integer primary key autoincrement, "
                + KEY_TITLE + " text not null, " 
                + KEY_BODY + " text not null, " 
                + KEY_DATE_TIME + " text not null);"; 

Here I get the path of the image in the gallery and then set the image in the image view

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == PICK_FROM_FILE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);

            Log.v("IMAGE PATH====>>>> ",selectedImagePath);

         // Decode, scale and set the image.
            Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagePath);
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(myBitmap, NEW_WIDTH, NEW_HEIGHT, true);
            myBitmap.recycle();
            myBitmap = null;

            mImageView.setImageBitmap(scaledBitmap);

        }
    }
}
4

3 回答 3

3

首先创建这样的表 db.execSQL("如果不存在则创建表 tablename(....,images BLOB,.....);");

然后像这样做你的java代码,

  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  Bitmap bit = BitmapFactory.decodeFile("your image path here");
  bit.compress(CompressFormat.PNG, 0, outputStream);

  SQLiteDatabase db = dbh.getWritableDatabase();
  ContentValues cv = new ContentValues();
  ..
 cv.put("images", outputStream.toByteArray());
 ..
 ..
db.insert("tablename", null, cv);
db.close();

这会将您的图像存储到数据库,并且,

byte []temp = c.getBlob(3);
Bitmap image = BitmapFactory.decodeByteArray(temp, 0, temp.length);
BitmapDrawable dd = new BitmapDrawable(image.getImage());
imgView.setBackgroundDrawable(dd);

这将从数据库中检索图像..

于 2012-06-04T09:59:43.750 回答
2

不是一个好主意..您应该将图像保存在磁盘上以减少 sql 操作并提高应用程序性能.. 将图像保存在数据库中会使数据库在各种意义上都变得沉重.. 只需将图像存储在磁盘上所需的位置并保存路径以及图像名称作为数据库表中的字符串。

于 2012-06-04T10:11:12.317 回答
2

或者,您将图像保存在手机内存(SD 卡上)或应用程序缓存等中,然后将检索图像文件的路径存储在 SQL 数据库中。

于 2012-06-04T09:55:48.163 回答