如何在Android中以共享首选项保存图像Android中使用Image的共享首选项问题

时间:2013-08-06 05:33:12

标签: android image sharedpreferences

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

我正在尝试类似的东西 -

SharedPreferences myPrefrence;
    String namePreferance="name";

    String imagePreferance="image";

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

我试图将图像转换为对象后将其保存为字符串。但当我将其重新转换为位图时,我没有得到任何东西。

4 个答案:

答案 0 :(得分:45)

我解决了你的问题,做了类似的事情:

  1. Write方法将位图编码为字符串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. 当您想在任何地方显示图像时,请使用解码方法将其再次转换为位图:

    // 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. 请在此方法中传递您的字符串并执行您想要的操作。

答案 1 :(得分:4)

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;
    }

我希望它对你有所帮助。

答案 2 :(得分:3)

编码到Base64 ?!这是一个疯狂的谈话!这就是你存储在共享偏好中的太多信息。您应该采取的策略是保存Image URI文件路径,并按原样检索它。通过这种方式,您的应用程序将无法存储如此多的信息,并在解码图像时成为内存耗尽。

我在Github上创建了一个简单的应用程序来演示这个想法,如果你想遵循:

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。

答案 3 :(得分:-1)

//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;
    }
}