以下是一个将图片保存在SharedPreferences中并显示的解决方案的代码示例:
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;
}
}
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);
}
}
}
注意:在实际的应用程序中,最好使用异步任务或其他方式来处理图片的保存和加载,以避免在主线程中执行耗时操作。