Android: 如何将 ImageView 保存到 SharedPreferences 以进行保存和检索?

Android: How do I save an ImageView to SharedPreferences for save and retrieve?

我正在创建一个应用程序,目前想知道如何将图像保存到 SharedPreferences,然后检索相同的图像,请参阅下面我拥有的有关图像的代码。我需要添加什么?

 public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    // Checks if the intent was able to pick the image and if it was successful
    if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && data != null){

        // Get selected image uri from phone gallery
        Uri selectedImage = data.getData();

        // Display selected photo in image view
        imageView.setImageURI(selectedImage);
    }

    // Handle Camera Request
    else if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK && data != null){

        // Bitmap variable to store data
        Bitmap bitmap = (Bitmap)data.getExtras().get("data");

        // Display taken picture in image view
        imageView.setImageBitmap(bitmap);
    }


    else if (requestCode == GALLERY_REQUEST_AFTER && resultCode == RESULT_OK && data != null){

        Uri selectedImageAfter = data.getData();

        imageView2.setImageURI(selectedImageAfter);
    }

    else if (requestCode == CAMERA_REQUEST_AFTER && resultCode == RESULT_OK && data != null){

        Bitmap bitmapAfter = (Bitmap)data.getExtras().get("data");

        imageView2.setImageBitmap(bitmapAfter);
    }
}

我一直使用这个库,它让事情变得更简单:implementation 'com.blankj:utilcodex:1.30.0'

以下两种方法可以让您使用SharedPreferences

保存和存储保存的图像路径
   public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Checks if the intent was able to pick the image and if it was successful
        if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && data != null) {

            // Get selected image uri from phone gallery
            Uri selectedImage = data.getData();

            // Display selected photo in image view
            imageView.setImageURI(selectedImage);

            //Store image path
            String imagePath = UriUtils.uri2File(selectedImage).getAbsolutePath();
            storeImage(imagePath);
        }

        // Handle Camera Request
        else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK && data != null) {

            // Bitmap variable to store data
            Bitmap bitmap = (Bitmap) data.getExtras().get("data");

            // Display taken picture in image view
            imageView.setImageBitmap(bitmap);


            //Save and store image path
            saveImage(bitmap);

        } else if (requestCode == GALLERY_REQUEST_AFTER && resultCode == RESULT_OK && data != null) {

            Uri selectedImageAfter = data.getData();

            imageView2.setImageURI(selectedImageAfter);
            
            
            //Store image path
            String imagePath = UriUtils.uri2File(selectedImageAfter).getAbsolutePath();
            storeImage(imagePath);
            
        } else if (requestCode == CAMERA_REQUEST_AFTER && resultCode == RESULT_OK && data != null) {

            Bitmap bitmapAfter = (Bitmap) data.getExtras().get("data");

            imageView2.setImageBitmap(bitmapAfter);


            //Save and store image path
            saveImage(bitmapAfter);
            
        }
    }


    public void storeImage(String imagePath) {
        SPUtils.getInstance().put("savedImage", imagePath);
    }

    public void saveImage(Bitmap bitmap) {
        //Save image to device storage
        File imageFile = new File(PathUtils.getExternalPicturesPath(), "cachedImage.jpg");
        boolean isSaved = ImageUtils.save(bitmap, imageFile, Bitmap.CompressFormat.JPEG);
        if (isSaved) storeImage(imageFile.getAbsolutePath());
    }

要获取存储的图像,请使用以下命令:

public void loadImage() {
        //Load the saved Image
        String imagePath = SPUtils.getInstance().getString("savedImage");
        Glide.with(this)
                .asBitmap()
                .load(imagePath)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

如果要保存和恢复与 ImageView 关联的 Bitmap,可以在 SharedPreferences.

中保存此位图的 Base64 编码

这是一个例子,

//get SharedPreferences
private static final String PREF_BITMAP_KEY = "PREF_BITMAP_KEY";
SharedPreferences prefs = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);

//get Bitmap and Base64 encoding
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

byte[] bytes = baos.toByteArray();
String b64 = Base64.encodeToString(bytes, Base64.DEFAULT);

//save in SharedPreference
prefs.edit().putString(PREF_BITMAP_KEY, b64);
prefs.edit().commit();

恢复位图:

String b64 = prefs.getString(PREF_BITMAP_KEY, null); 
if (!TextUtils.isNullOrEmpty(b64)) {
  byte[] bytes = Base64.decode(b64, Base64.DEFAULT);
  Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  imageView.setImageBitmap(bitmap);
}