我如何讓用戶將圖庫中的影像保存到他的 SharedPreferences?我現在正在使用此代碼,以便用戶可以從他喜歡的圖庫中選擇影像。我如何將他選擇的圖片保存到 SharedPreferences?
if(v.getId()==R.id.btnUploadPicture)
{
Intent uploadPic = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
final int ACTIVITY_SELECT_IMAGE = 1234;
startActivityForResult(uploadPic, ACTIVITY_SELECT_IMAGE);
}
uj5u.com熱心網友回復:
您可以在共享首選項中保存影像路徑,然后從共享首選項中獲取影像路徑。
可以這樣獲取影像路徑。
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTIVITY_SELECT_IMAGE && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
Uri tempUri = getImageUri(getApplicationContext(), photo);
File finalFile = new File(getRealPathFromURI(tempUri));
System.out.println(mImageCaptureUri);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
uj5u.com熱心網友回復:
如果我錯了糾正我。但聽起來真正的問題是,當您從 startActivityForResult 回傳時,您不知道如何處理影像。當您使用 startActivityForResult 時,onActivityResult 在從所述活動回傳時始終運行。你需要在你的類中覆寫 onActivityResult 。
我建議制作
final int ACTIVITY_SELECT_IMAGE = 1234;
一個全域變數,因此您可以在 startActivityForResult 中使用它。因為您需要用 if 陳述句包圍您的代碼,以便在從另一個活動回傳時不會運行它。
將以下覆寫方法放在您的類中。
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ACTIVITY_SELECT_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
System.out.println("Successfully Returned from Gallery with Image")
//This is your image from the gallery
if (data != null) {
Uri fileUri = data.getData();
//This is where you will do what you need with the image.
//Maybe set an ImageView
//imageView.setImageURI(fileUri);
//Or you can copy the image to the app's gallery
//Add URI to SharedPrefs
}
} else if (resultCode == Activity.RESULT_ERROR) {
Toast.makeText(this, "An Error Has Occurred", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/334736.html
