Android -- 使用Sharepreference保存Bitmap,drawable和object类型数据

本文介绍了一个工具类ShareBitmapUtils,该工具类提供了使用SharedPreferences在Android应用程序中存储和读取Bitmap、Drawable及Object的方法。通过Base64编码和字节流操作实现图片和其他对象的有效存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自:https://blog.csdn.net/zhangyalong_android/article/details/52702858

一. 工具类

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

/**
 * shareprefence保存和提取bitmap,drawable,object
 */
public class ShareBitmapUtils {

    private static final String MY_PREFERENCE = "set";

    public static boolean putBitmap(Context context, String key, Bitmap bitmap) {
        SharedPreferences sp = context.getSharedPreferences(MY_PREFERENCE,
                Context.MODE_PRIVATE);

        paraCheck(sp, key);
        if (bitmap == null || bitmap.isRecycled()) {
            return false;
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            String imageBase64 = new String(Base64.encode(baos.toByteArray(),
                    Base64.DEFAULT));
            SharedPreferences.Editor e = sp.edit();
            e.putString(key, imageBase64);
            return e.commit();
        }
    }

    public static Bitmap getBitmap(Context context, String key,
                                   Bitmap defaultValue) {
        SharedPreferences sp = context.getSharedPreferences(MY_PREFERENCE,
                Context.MODE_PRIVATE);

        paraCheck(sp, key);
        String imageBase64 = sp.getString(key, "");
        if (TextUtils.isEmpty(imageBase64)) {
            return defaultValue;
        }

        byte[] base64Bytes = Base64.decode(imageBase64.getBytes(),
                Base64.DEFAULT);
        ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
        Bitmap ret = BitmapFactory.decodeStream(bais);
        if (ret != null) {
            return ret;
        } else {
            return defaultValue;
        }
    }

    private static void paraCheck(SharedPreferences sp, String key) {
        if (sp == null) {
            throw new IllegalArgumentException();
        }
        if (TextUtils.isEmpty(key)) {
            throw new IllegalArgumentException();
        }
    }

    public static boolean putDrawable(Context context, String key, Drawable d) {
        SharedPreferences sp = context.getSharedPreferences(MY_PREFERENCE,
                Context.MODE_PRIVATE);
        paraCheck(sp, key);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ((BitmapDrawable) d).getBitmap()
                .compress(Bitmap.CompressFormat.JPEG, 50, baos);
        String imageBase64 = new String(Base64.encode(baos.toByteArray(),
                Base64.DEFAULT));
        SharedPreferences.Editor e = sp.edit();
        e.putString(key, imageBase64);
        return e.commit();
    }

    public static Drawable getDrawable(Context context, String key,
                                       Drawable defaultValue) {
        SharedPreferences sp = context.getSharedPreferences(MY_PREFERENCE,
                Context.MODE_PRIVATE);
        paraCheck(sp, key);
        String imageBase64 = sp.getString(key, "");
        if (TextUtils.isEmpty(imageBase64)) {
            return defaultValue;
        }

        byte[] base64Bytes = Base64.decode(imageBase64.getBytes(),
                Base64.DEFAULT);
        ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
        Drawable ret = Drawable.createFromStream(bais, "");
        if (ret != null) {
            return ret;
        } else {
            return defaultValue;
        }
    }

    public static boolean putObject(Context context, String key, Object obj) {
        SharedPreferences sp = context.getSharedPreferences(MY_PREFERENCE,
                Context.MODE_PRIVATE);
        paraCheck(sp, key);
        if (obj == null) {
            SharedPreferences.Editor e = sp.edit();
            e.putString(key, "");
            return e.commit();
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = null;
            try {
                oos = new ObjectOutputStream(baos);
                oos.writeObject(obj);
            } catch (IOException e1) {
                e1.printStackTrace();
                return false;
            }
            String objectBase64 = new String(Base64.encode(baos.toByteArray(),
                    Base64.DEFAULT));
            SharedPreferences.Editor e = sp.edit();
            e.putString(key, objectBase64);
            return e.commit();
        }
    }

    public static Object getObject(Context context, String key,
                                   Object defaultValue) {
        SharedPreferences sp = context.getSharedPreferences(MY_PREFERENCE,
                Context.MODE_PRIVATE);
        paraCheck(sp, key);
        String objectBase64 = sp.getString(key, "");
        if (TextUtils.isEmpty(objectBase64)) {
            return defaultValue;
        }
        byte[] base64Bytes = Base64.decode(objectBase64.getBytes(),
                Base64.DEFAULT);
        ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
        ObjectInputStream ois;
        try {
            ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (StreamCorruptedException e) {
            // e.printStackTrace();
            return null;
        } catch (IOException e) {
            // e.printStackTrace();
            return null;
        } catch (ClassNotFoundException e) {
            // e.printStackTrace();
            return null;
        }
    }

    public static boolean isObjectEqual(Context context, String key,
                                        Object newValue) {
        SharedPreferences sp = context.getSharedPreferences(MY_PREFERENCE,
                Context.MODE_PRIVATE);
        paraCheck(sp, key);
        if (newValue == null) {
            return false;
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = null;
            try {
                oos = new ObjectOutputStream(baos);
                oos.writeObject(newValue);
            } catch (IOException e1) {
                e1.printStackTrace();
                return false;
            }
            String newValueBase64 = new String(Base64.encode(
                    baos.toByteArray(), Base64.DEFAULT));
            String oldValueBase64 = sp.getString(key, "");
            return newValueBase64.equals(oldValueBase64);
        }
    }

}

二. 调用

ShareBitmapUtils.putBitmap(getActivity(), "infoImage", head
ShareBitmapUtils.getBitmap(getActivity(), "infoImage", head


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值