Android:将图片保存在SharedPreferences中并显示它
创始人
2024-10-13 13:01:00
0

以下是一个将图片保存在SharedPreferences中并显示的解决方案的代码示例:

  1. 在AndroidManifest.xml文件中添加以下权限:

  1. 创建一个名为ImageUtils的辅助类:
public class ImageUtils {
    public static void saveImage(Context context, Bitmap bitmap, String key) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imageBytes = baos.toByteArray();

        SharedPreferences.Editor editor = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE).edit();
        editor.putString(key, Base64.encodeToString(imageBytes, Base64.DEFAULT));
        editor.apply();
    }

    public static Bitmap loadImage(Context context, String key) {
        SharedPreferences prefs = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
        String imageString = prefs.getString(key, "");

        if (!imageString.isEmpty()) {
            byte[] imageBytes = Base64.decode(imageString, Base64.DEFAULT);
            return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        }

        return null;
    }
}
  1. 在Activity中使用上述辅助类来保存和加载图片:
public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private Bitmap imageBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView);

        // 保存图片
        imageBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
        ImageUtils.saveImage(this, imageBitmap, "my_image");

        // 加载并显示图片
        Bitmap loadedImage = ImageUtils.loadImage(this, "my_image");
        if (loadedImage != null) {
            imageView.setImageBitmap(loadedImage);
        }
    }
}

注意:在实际的应用程序中,最好使用异步任务或其他方式来处理图片的保存和加载,以避免在主线程中执行耗时操作。

相关内容

热门资讯

安装程序教程!aapoker脚... 安装程序教程!aapoker脚本,aapoker怎么控制牌,必胜教程(有挂神器)是一款可以让一直输的...
实测交流!聚星ai辅助工具下载... 实测交流!聚星ai辅助工具下载,wpk安卓下载辅助,科技教程(有挂透视)1、点击下载安装,微扑克wp...
必看攻略!wepoker透视a... 必看攻略!wepoker透视app下载,wpk模拟器,2025新版教程(有挂透明);玩家必备必赢加哟...
总算清楚!hhpoker到底可... 总算清楚!hhpoker到底可以作弊码,pokemmo手机脚本辅助器,2025新版教程(有挂方法);...
记者爆料!约局吧能不能开挂,w... 此外,数据分析德州(约局吧能不能开挂)辅助神器app还具备辅助透视行为开挂功能,通过对客户约局吧能不...
技术分享!wepoker辅助器... 技术分享!wepoker辅助器官方,sohoo辅助,软件教程(有挂技巧)准备好在wepoker辅助器...
信息共享!cloudpoker... 这是一款非常优秀的cloudpoker怎么开挂 ia辅助检测软件,能够让你了解到cloudpoker...
推荐十款!wepoker透视脚... 推荐十款!wepoker透视脚本视频,hhpoker买挂,安装教程(有挂神器);科技安装教程;136...
科普攻略!aapoker辅助怎... 科普攻略!aapoker辅助怎么用,hhpoker有后台操作吗,安装教程(有挂技巧)1、点击下载安装...
玩家必看教程!竞技联盟破解版最... 玩家必看教程!竞技联盟破解版最新版,云扑克有透视吗,技巧教程(有挂辅助)这是由厦门游乐互动科技有限公...