如何在Android 中的共享首选项中保存图像|Android 中的共享偏好问题与图像 [英] How to save Image in shared preference in Android | Shared preference issue in Android with Image

查看:20
本文介绍了如何在Android 中的共享首选项中保存图像|Android 中的共享偏好问题与图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我登录后的应用程序中,我必须在其他页面的共享首选项中保存用户名和图像.我可以优先保存名称,但找不到任何保存图像的位置.

In my application after login I have to save user name and image in shared preference for other pages. I am able to save name in preference but can't get any where how to save image.

我正在尝试类似的东西-

I am trying something like that-

SharedPreferences myPrefrence;
    String namePreferance="name";

    String imagePreferance="image";

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

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

I am trying to save image as string after convert it into object. But when I reconvert it into bitmap I did not get anything.

推荐答案

我解决了您的问题,请执行以下操作:

I solved your problem do something like that:

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

  1. Write Method to encode your bitmap into string 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;
}

  • 在这个方法中传递你的位图,就像你喜欢的东西一样:

  • Pass your bitmap inside this method like something in your preference:

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

  • 如果您想在任何地方显示您的图像,请使用解码方法再次将其转换为位图:

  • And when you want to display your image just anywhere, convert it into a bitmap again using the decode method:

    // method for base64 to bitmap
    public static Bitmap decodeBase64(String input) {
        byte[] decodedByte = Base64.decode(input, 0);
        return BitmapFactory
                .decodeByteArray(decodedByte, 0, decodedByte.length);
    }
    

  • 请在此方法中传递您的字符串并执行您想要的操作.

  • Please pass your string inside this method and do what you want.

    这篇关于如何在Android 中的共享首选项中保存图像|Android 中的共享偏好问题与图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆