首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android:如何将ImageView保存到SharedPreferences以保存和检索?

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

Stack Overflow用户
提问于 2021-03-19 12:41:06
回答 2查看 108关注 0票数 1

我正在创建一个应用程序,并且正在考虑如何将图像保存到SharedPreferences,然后检索相同的图像,请参阅下面有关图像的代码。我还需要补充些什么?

代码语言:javascript
复制
 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);
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-03-22 09:13:12

如果要保存和还原与ImageView关联的ImageView,可以在SharedPreferences中保存此位图的Base64编码。

以下是一个例子,

代码语言:javascript
复制
//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();

要恢复位图,请执行以下操作:

代码语言:javascript
复制
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);
}
票数 1
EN

Stack Overflow用户

发布于 2021-03-19 13:46:13

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

以下两种方法允许您使用SharedPreferences保存和存储保存的图像路径

代码语言:javascript
复制
   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());
    }

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

代码语言:javascript
复制
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) {

                    }
                });
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66708379

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档