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.
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);
}
}
}
first create table like this db.execSQL("create table if not exists tablename(....,images BLOB,.....);");
then do your java code like this,
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();
this will store your image to db and,
byte []temp = c.getBlob(3);
Bitmap image = BitmapFactory.decodeByteArray(temp, 0, temp.length);
BitmapDrawable dd = new BitmapDrawable(image.getImage());
imgView.setBackgroundDrawable(dd);
this will retrive image from db..
或者,将图像保存在手机内存(SD卡上)或应用程序缓存等中。然后在SQL数据库中存储用于检索图像文件的路径。
这不是一个好主意。您应该将映像保存在磁盘上,以减少sql操作并提高应用程序性能。.在DB中保存映像将在各种意义上使数据库变重。.只需将映像存储在磁盘上的所需位置并保存路径以及图像名称作为数据库表中的字符串。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.