如何将ImageView图片存入SharedPreference并在其他Activity的GridView中显示
注意:SharedPreferences是基于XML的轻量键值存储,仅支持存储基础类型与字符串,无法直接存Bitmap,需先将图片转成Base64编码字符串存储,该方案仅适合小体积图标/缩略图,大尺寸图片请存本地文件、SP中仅保存文件路径,避免引发ANR、内存溢出问题
一、存储图片到SharedPreferences
- 从目标ImageView中提取承载的Bitmap对象
- 将Bitmap按指定画质压缩为字节数组,转码为Base64字符串
- 将字符串写入SP对应key下
// 从ImageView提取Bitmap ImageView sourceIv = findViewById(R.id.source_imageview); sourceIv.setDrawingCacheEnabled(true); Bitmap sourceBmp = Bitmap.createBitmap(sourceIv.getDrawingCache()); sourceIv.setDrawingCacheEnabled(false); // Bitmap转Base64字符串 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // 压缩格式选JPEG可减小体积,画质参数按需调整,透明图请换PNG格式 sourceBmp.compress(Bitmap.CompressFormat.JPEG, 70, outputStream); byte[] bmpBytes = outputStream.toByteArray(); String bmpBase64 = Base64.encodeToString(bmpBytes, Base64.DEFAULT); // 写入SharedPreferences SharedPreferences sp = getSharedPreferences("local_img_sp", MODE_PRIVATE); sp.edit() // 多图存储请给每个key加唯一标识,比如拼接图片ID/时间戳,避免覆盖旧数据 .putString("img_item_" + System.currentTimeMillis(), bmpBase64) .apply();
二、跨页面在GridView读取展示
- 在目标Activity中读取SP下所有存储的图片Base64字段
- 将Base64字符串解码回Bitmap对象,整理为GridView的数据源
- 自定义GridView适配器,在条目渲染时将Bitmap设置到对应ImageView上
// 读取SP中所有存储的图片 SharedPreferences sp = getSharedPreferences("local_img_sp", MODE_PRIVATE); List<Bitmap> showImgList = new ArrayList<>(); Map<String, ?> spAllContent = sp.getAll(); for (Map.Entry<String, ?> entry : spAllContent.entrySet()) { // 过滤非图片类的SP字段 if (entry.getKey().startsWith("img_item_")) { String base64Content = (String) entry.getValue(); byte[] bmpBytes = Base64.decode(base64Content, Base64.DEFAULT); Bitmap showBmp = BitmapFactory.decodeByteArray(bmpBytes, 0, bmpBytes.length); showImgList.add(showBmp); } } // 绑定适配器到GridView GridView imgGridView = findViewById(R.id.show_gridview); // 替换为自己实现的GridView适配器,传入showImgList作为数据源即可完成渲染 imgGridView.setAdapter(new ImgGridAdapter(this, showImgList));
注意事项
- Base64编解码、Bitmap压缩操作建议放到子线程执行,不要阻塞主线程
- 单张图片转Base64后长度建议不超过50KB,否则SP加载会出现明显卡顿
- 如果图片数量多、分辨率高,直接改用「SP存文件路径、图片存应用私有目录」的方案,不要硬存Base64字符串
内容的提问来源于stack exchange,提问作者Ashok Poojari
相关产品推荐
相关产品推荐

