我想创建一个数据库,用于存储用户库中的图像,图像是位图的形式。我已经有一个简单的数据库存储名称等文本,我想知道你是否知道一种方法我只需将图像添加到我现有的数据库中。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Button pic = (Button) findViewById(R.id.button2);
pic.setVisibility(View.GONE);
ImageView picture = (ImageView) findViewById(R.id.imageView);
picture.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Intent intent = new Intent(this, recipelayout.class);
intent.putExtra("BitmapImage", picturePath);
}
}
答案 0 :(得分:0)
是的,你可以。
首先,将您的图片转换为字节数组:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
byte data = outputStream.toByteArray();
然后将其作为blob写入DB:
SQLiteProgram prog = sqlite.compileStatement("insert into ...... values(?, ?)");
p.bindBlob(1, data);
p.execute();
上述方法是可行的,但从我自己的经验来看,性能低于简单写作 您的图像到内部存储器并在数据库中保存其路径:
A. 将图像写入应用程序的内存
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("MyInternalDir", Context.MODE_PRIVATE);
File mypath = new File(directory, "fileName.jpg");
Bitmap bitmapImage = BitmapFactory.decodeFile(picturePath); //<----- or from any other source...
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
String filePath = directory.getAbsolutePath();
B。并将filePath存储为DB
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("ImagePath", filePath);
database.insert(....);
我更喜欢后一种方法。随意选择自己的。