简体   繁体   English

从相机获取图像或从图库上传并在 ImageView (Android Studio) 中显示后,保存图像为 SharedPreferences

[英]Save image is SharedPreferences after Image is get from camera or upload from gallery and display at ImageView (Android Studio)

I have a problem as mention at the question above.我在上面的问题中提到了一个问题。 All data from EditText, RadioButton and Spinner can be saved at SharedPreference and display back at another activity.来自 EditText、RadioButton 和 Spinner 的所有数据都可以保存在 SharedPreference 中并在另一个活动中显示回来。 But i dont know how to save the Image after I get it from camera or upload from gallery and display at ImageView.但是我不知道如何在从相机获取图像或从图库上传并在 ImageView 上显示后保存图像。 Any method?有什么方法吗? Please help me.请帮我。

//Code for saving in SharedPreferences //保存在SharedPreferences中的代码

    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("title",etTitle.getText().toString());
            editor.putString("year",etYear.getText().toString());
            editor.putString("month",etMonth.getText().toString());

            // get selected radio button from radioGroup
            int selectedId = rgSuggestWill.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            radioButton = findViewById(selectedId);
            editor.putString("suggestionwill",radioButton.getText().toString());
            if (spReviewer.getSelectedItem().toString().equals("Please choose")){

                AlertDialog alertDialog = new AlertDialog.Builder(NewSuggestion.this).create();
                alertDialog.setTitle("Alert");
                alertDialog.setMessage("Please choose your reviewer");
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alertDialog.show();
            }else{
                editor.putString("reviewer",spReviewer.getSelectedItem().toString());
                Intent intent = new Intent(NewSuggestion.this,NewSuggestion2.class);
                startActivity(intent);
            }
            editor.commit();
        }
    });

//code for recall from SharedPreferences // 从 SharedPreferences 调用的代码

SharedPreferences sharedPreferences = getSharedPreferences("MyData", MODE_PRIVATE);
    String title = sharedPreferences.getString("title",DEFAULT);
    String year = sharedPreferences.getString("year",DEFAULT);
    String month =  sharedPreferences.getString("month",DEFAULT);
    String present =  sharedPreferences.getString("present",DEFAULT);
    String details = sharedPreferences.getString("details",DEFAULT);
    String benefit =  sharedPreferences.getString("benefit",DEFAULT);
    String suggestionwill =  sharedPreferences.getString("suggestionwill",DEFAULT);
    String reviewer =  sharedPreferences.getString("reviewer",DEFAULT);

Do not store the image in SharedPreferences, you should save an image to sd-card and then save the image path from sd-card into SharedPreferences ->不要将图像存储在 SharedPreferences 中,您应该将图像保存到 sd-card,然后将图像路径从 sd-card 保存到 SharedPreferences ->

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.edit().putString("YourImagePathTag","YourImagePath").commit;

then you can get the image from this path.然后你可以从这个路径获取图像。 Also, you can save the path into the database which is safer than this.此外,您可以将路径保存到比这更安全的数据库中。

Don't save the image using preference, instead use the SQLite for saving and retrieving by use "blob"不要使用首选项保存图像,而是使用 SQLite 使用“blob”进行保存和检索

//Convert your bitmap to base64 //将位图转换为base64

public static String encodeBitmapTobase64(Bitmap image) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.PNG, 100, os);
    byte[] byteArray = baos.toByteArray();
    String encodedImageString = 
    Base64.getEncoder().encodeToString(byteArray);
    return encodedImageString ;
}

//Save the image in preferences //在首选项中保存图像

SharedPreferences.Editor prefEditor= myPrefrence.edit();
prefEditor.putString("key", encodeBitmapTobase64(yourbitmap));
prefEditor.commit();

// get encoded string from pref and convert base64 string to bitmap // 从 pref 获取编码字符串并将 base64 字符串转换为位图

public static Bitmap base64ToBitmap(String encodedString) {
    byte[] decodedString = Base64.decode(encodedString, Base64.DEFAULT);
    Bitmap bitmap= BitmapFactory.decodeByteArray(decodedString , 0, 
    decodedString.length);
    return bitmap;
}

saving the image in the sharedpreference(by string) is not a good method.将图像保存在共享首选项中(按字符串)不是一个好方法。 make the image to the bytearray or uri(after save in the EXTERNAL_STORAGE) and use the intent.putextra将图像制作为字节数组或 uri(在 EXTERNAL_STORAGE 中保存后)并使用 intent.putextra

When you're getting the selected image for example from gallery in onActivityResult() method then you can save the path string from Uri like this:例如,当您从 onActivityResult() 方法中的图库中获取所选图像时,您可以像这样从 Uri 保存路径字符串:

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

    // Result code is RESULT_OK only if the user selects an Image
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case GALLERY_REQUEST_CODE:
                //data.getData returns the content URI for the selected Image
                Uri selectedImage = data.getData();

                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
                sharedPreferences.edit().putString("KEY_IMAGE", selectedImage.getPath()).apply();
                break;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android-图像未显示在ImageView中并且无法从相机保存到图库 - Android - Image is not showing in ImageView and not save to gallery from camera Android ImageView无法从图库或相机中获取图像 - Android ImageView can't get image from gallery or camera Android:使用相机将图像显示到ImageView并保存到图库 - Android : Use Camera to display image to ImageView and Save to Gallery 无法将图像从 Android 中的 ImageView 保存到图库 - unable to save image to gallery from ImageView in Android 使用SharedPreferences将图像从画廊加载到ImageView - Load image from gallery to ImageView with SharedPreferences 如何从相机或图库中获取图像并上传到 Android Q 中的服务器? - How to get image from camera or gallery and upload to server in Android Q? 无法在Android 8和9中从相机和图库上传图片 - Not able to upload image from camera and gallery in Android 8 & 9 Android Webview从图库或相机上传图像 - Android Webview Upload Image from gallery or camera 从相机拍摄后将图像保存到图库 - save image to the gallery after taken from the camera 如何在图库中的imageView上设置图像以及在Android中由相机拍摄的图像? - How to set an image on imageView from the gallery and image taken by camera in Android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM