簡體   English   中英

使用SharedPreferences將圖像從畫廊加載到ImageView

[英]Load image from gallery to ImageView with SharedPreferences

我希望你能幫助我。 這是我第一次在這里寫問題。

我想從圖庫中選擇一個圖像並將其顯示在ImageView中。 關閉該活動並重新打開之后,我想顯示我們先前選擇的圖像。 選擇圖像->在ImageView中顯示圖像->保存圖像選擇->關閉活動->打開活動->顯示圖像選擇。 希望我足夠清楚。

從圖庫中選擇圖像並將其加載到ImageView的第一部分正在工作,給我帶來問題的是當前我正在嘗試將所選圖像或其路徑保存在SharedPreferences / Preferences中,但在再次打開活動時未顯示。 使用SharedPreferences / Preferences保存和加載似乎可以正常工作,但是不會顯示圖片。

我嘗試了以下方法:Path,EncodedPath等,但似乎沒有任何效果。 我究竟做錯了什么 ?

要打開畫廊:

    Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
    gallery.setType("image/*");
    startActivityForResult(gallery, RESULT_LOAD_IMAGE);

保存圖像:

   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
        Uri imageUri = data.getData();
        imageView.setImageURI(imageUri);

        SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("imageURI", imageUri.getEncodedPath());
        editor.commit();
    }
}

要加載所選圖像:

        SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
    String imageUriString = settings.getString("imageURI", "");
    Uri imageUri = Uri.parse(imageUriString);

    Picasso.with(this)
            .load(imageUriString)
            //.load(testarrraylogo.get(position))
            .placeholder(R.drawable.otto)
            .error(R.drawable.hochbahn)
            // To fit image into imageView
            .fit()
            // To prevent fade animation
            .noFade()
            .into(imageView);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("imageURI", imageUri.getEncodedPath());
editor.commit();

進入

SharedPreferences.Editor editor = getSharedPreferences("preference", 
MODE_PRIVATE).edit();
editor.putString("imageURI", "uriPathstring");  //Your URI PATH STRING
editor.apply();

像這樣檢索

SharedPreferences prefs = getSharedPreferences("preference, MODE_PRIVATE); 
String imageUri = prefs.getString("imageURI", null);

在畢加索中加載圖像

Picasso.with(context).load(new File(imageuri)).into(imageView);

第一次檢索不使用Picasso加載圖像的圖像時,可以替換此imageView.setImageURI(imageUri); 與此Picasso.with(YourActivity.this).load(imageData).into(imageView)

然后將Uri保存到SharedPreferences,您可以執行以下操作: editor.putString("imageURI", imageUri.toString); 然后用

try {
   imageUri = URI.create(myPrefs.getString("imageURI", "defaultString"));
} catch (IllegalArgumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM