14

在登录后的应用程序中,我必须将用户名和图像保存在其他页面的共享首选项中。我可以优先保存名称,但不知道如何保存图像。

我正在尝试类似的东西-

SharedPreferences myPrefrence;
    String namePreferance="name";

    String imagePreferance="image";

SharedPreferences.Editor editor = myPrefrence.edit();
                editor.putString("namePreferance", itemNAme);
                editor.putString("imagePreferance", itemImagePreferance);
                editor.commit();

我试图将图像转换为对象后将其保存为字符串。但是当我将它重新转换为位图时,我什么也没得到。

4

4 回答 4

53

我解决了你的问题做这样的事情:

  1. 编写方法将您的位图编码为字符串 base64-

    // method for bitmap to base64
    public static String encodeTobase64(Bitmap image) {
        Bitmap immage = image;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
    
        Log.d("Image Log:", imageEncoded);
        return imageEncoded;
    }
    
  2. 在此方法中传递您的位图,就像您喜欢的一样:

    SharedPreferences.Editor editor = myPrefrence.edit();
    editor.putString("namePreferance", itemNAme);
    editor.putString("imagePreferance", encodeTobase64(yourbitmap));
    editor.commit();
    
  3. 当您想在任何地方显示图像时,请使用 decode 方法再次将其转换为位图:

    // method for base64 to bitmap
    public static Bitmap decodeBase64(String input) {
        byte[] decodedByte = Base64.decode(input, 0);
        return BitmapFactory
                .decodeByteArray(decodedByte, 0, decodedByte.length);
    }
    
  4. 请在此方法中传递您的字符串并执行您想要的操作。

于 2013-08-07T04:42:34.940 回答
6
Finally I solved this problem.

步骤:- 1. 我在 onCreate() 中编写了一些代码,用于从之前的 Activity 中获取意图数据

 private  Bitmap bitmap;

 Intent intent = getIntent();

        if (getIntent().getExtras() != null)
        {
            // for get data from intent

            bitmap = intent.getParcelableExtra("PRODUCT_PHOTO");

            // for set this picture to imageview

            your_imageView.setImageBitmap(bitmap);

             sharedPreferences();

        }else
        {
            retrivesharedPreferences();
        }

2 创建 sharedPreferences() 并把这段代码

 private void sharedPreferences()
    {
        SharedPreferences shared = getSharedPreferences("App_settings", MODE_PRIVATE);
        SharedPreferences.Editor editor = shared.edit();
        editor.putString("PRODUCT_PHOTO", encodeTobase64(bitmap));
        editor.commit();
    }

3创建retrivesharedPreferences()这个方法并放上这段代码,

private void retrivesharedPreferences()
    {
      SharedPreferences shared = getSharedPreferences("MyApp_Settings", MODE_PRIVATE);
        String photo = shared.getString("PRODUCT_PHOTO", "photo");
        assert photo != null;
        if(!photo.equals("photo"))
        {
            byte[] b = Base64.decode(photo, Base64.DEFAULT);
            InputStream is = new ByteArrayInputStream(b);
            bitmap = BitmapFactory.decodeStream(is);
            your_imageview.setImageBitmap(bitmap);
        }

    }

4 编写 encodeTobase64() 方法将您的位图编码为字符串 base64- 并将代码放入此方法中

 public static String encodeTobase64(Bitmap image) {
        Bitmap bitmap_image = image;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap_image.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

        return imageEncoded;
    }

我希望它对你有帮助。

于 2015-07-29T13:45:19.480 回答
4

编码为 Base64?!那是疯话!您存储到共享首选项中的信息太多了。您应该采取的策略是保存图像 URI 文件路径,然后按原样检索它。这样,您的应用程序就不会在解码图像时存储太多信息并成为内存占用者。

我在Github上做了一个简单的 App来演示这个想法,如果你想遵循:

1. 声明变量:

private ImageView mImage;
private Uri mImageUri;

2. 选择图片:

public void imageSelect() {
     Intent intent;
     if (Build.VERSION.SDK_INT < 19) {
         intent = new Intent(Intent.ACTION_GET_CONTENT);
     } else {
         intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
         intent.addCategory(Intent.CATEGORY_OPENABLE);
     }
     intent.setType("image/*");
     startActivityForResult(Intent.createChooser(intent, "Select Picture"),
         PICK_IMAGE_REQUEST);
 }

3. 保存图片 URI:

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     // Check which request we're responding to
     if (requestCode == PICK_IMAGE_REQUEST) {
         // Make sure the request was successful
         if (resultCode == RESULT_OK) {
             // The user picked a image.
             // The Intent's data Uri identifies which item was selected.
            if (data != null) {

                // This is the key line item, URI specifies the name of the data
                mImageUri = data.getData();

                // Removes Uri Permission so that when you restart the device, it will be allowed to reload. 
                this.grantUriPermission(this.getPackageName(), mImageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
                this.getContentResolver().takePersistableUriPermission(mImageUri, takeFlags);

                // Saves image URI as string to Default Shared Preferences
                SharedPreferences preferences = 
                     PreferenceManager.getDefaultSharedPreferences(this);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("image", String.valueOf(mImageUri));
                editor.commit();

                // Sets the ImageView with the Image URI
                mImage.setImageURI(mImageUri);
                mImage.invalidate();
             }
         }
     }
 }

4. 需要时检索图像 URI:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String mImageUri = preferences.getString("image", null);
mImage.setImageURI(Uri.parse(mImageUri));

就是这样!现在我们已经干净地将图像 uri 路径保存到共享首选项,并且没有浪费宝贵的系统资源对图像进行编码并将其保存到 SharedPreferences。

于 2017-08-16T07:31:54.757 回答
0
//Thanks Maish srivastava 
// i will do complete code just copy past and run it sure worked it
//
public class MainActivity extends Activity  implements OnClickListener
{
    private static int RESULT_LOAD_IMAGE = 1;
    public static final String MyPREFERENCES = "MyPre" ;//file name
       public static final String  key = "nameKey"; 
       SharedPreferences sharedpreferences ;
       Bitmap btmap;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         sharedpreferences =  getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
         if (sharedpreferences.contains(key))
          {
                String u=sharedpreferences.getString(key, "");
                btmap=decodeBase64(u); 
                ImageView iv = (ImageView) findViewById(R.id.imageView1);
                iv.setImageBitmap(btmap);
          }
       ImageButton imgbtn=(ImageButton) findViewById(R.id.imageButton1);
       imgbtn.setOnClickListener(this);
    }

public void onClick(View  v) 
{
    // TODO Auto-generated method stub
    switch (v.getId())
     {
             case R.id.imageButton1: 
                  try 
                  { //go to image library and pick the image
                   Intent i=newIntent(ntent.ACTION_PICK,
                   android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                   startActivityForResult(i, RESULT_LOAD_IMAGE);      
                  } 
                  catch (Exception e) 
                  {
                   e.printStackTrace();
                  }
                  break;
     }  
}
@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();

        ImageView iv = (ImageView) findViewById(R.id.imageView1);
        iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        btmap=BitmapFactory.decodeFile(picturePath);//decode method called

        Editor editor = sharedpreferences.edit();
        editor.putString(key,  encodeTobase64(btmap));
        editor.commit();   
    }


}
public static String encodeTobase64(Bitmap image)
     {
    Bitmap immage = image;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

    Log.d("Image Log:", imageEncoded);
    return imageEncoded;

     }
public static Bitmap decodeBase64(String input) 
{
    byte[] decodedByte = Base64.decode(input, 0);
    return BitmapFactory
            .decodeByteArray(decodedByte, 0, decodedByte.length);
}
@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}
于 2014-12-26T17:49:59.650 回答