我正在做一個用戶選擇圖像的項目,我們必須存儲圖像的路徑。我可以在imageView
中顯示圖片,但是當應用程序關閉或用戶按下後退按鈕圖像時不顯示。所以我必須永遠保存圖像直到用戶刪除圖像。如何檢索存儲在數據庫中的圖像路徑並在圖像視圖中顯示?
以下是我的代碼:
Button buttonLoadImage = (Button) findViewById(R.id.pre1);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
@SuppressWarnings("unused")
@Override
protected 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();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath);
//testimage.setImageBitmap(yourSelectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
ImageView imageView = (ImageView) findViewById(R.id.im2);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
pd.open();
pd.insert(picturePath);
pd.close();
}
}
您可以將imagePath存儲在某處,如sqlite Db或sharedpref或文件系統 –