如何在saredPreference中保存裁剪的图像URI?

时间:2015-10-16 06:33:13

标签: android image sharedpreferences

我正在做一个应用程序将图像从图库保存到ImageView,为此我必须保存在sharedPreference中,当我离开应用程序并返回时,图像仍然存在。

ps:我已经在这里读过一个问题,但是对我来说并不适用

有人可以帮助我吗?请

JAVA文件的一部分

++++++++++++++++++++++++

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("data",  context.MODE_PRIVATE);


imgButton = (ImageView) findViewById(R.id.AddPic);
imgButton.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) {
        Intent GaleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(GaleryIntent, RESULT_LOAD_IMAGE);
    } 
}); 


} 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
    SelectedImage = data.getData();



  performCrop();


} 

else if(requestCode == PIC_CROP){

    Bundle extras = data.getExtras();
    //get the cropped bitmap
    Bitmap thePic = extras.getParcelable("data");


    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    thePic.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap    object   
    byte[] byteArray = baos.toByteArray();

    String imageString= Base64.encodeToString(byteArray , Base64.DEFAULT);

    byte[] imageBytes = Base64.decode(imageString.getBytes());
    imgButton.setImageBitmap(BitmapFactory.decodeByteArray(imageBytes, 0,    imageBytes.length));



}
}
private void performCrop() {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP"); 
        cropIntent.setDataAndType(SelectedImage, "image/*");
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("outputX", 256);
        cropIntent.putExtra("outputY", 256);
        cropIntent.putExtra("return-data", true);
        startActivityForResult(cropIntent, PIC_CROP);
    }
    catch(ActivityNotFoundException anfe){
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }       
}}

+++++++++++++++++++++++++

我试过这个,第一个答案:How to save cropped image uri in shared Preference 但没有工作

也许我必须将位图转换为字符串或做其他事情,但我不知道

无论如何,无论如何

2 个答案:

答案 0 :(得分:0)

您可以在SharedPreference中保存裁剪的图像位图。因为我们只能在SharedPreference中存储Boolean,Float,Int,Long,String值。但是你可以做的一件事就是将Bitmap转换为Base64 String并保存在SharedPreference中,然后在用户打开应用程序时检索字符串..

将位图转换为字节数组,如下所示:

ByteArrayOutputStream baos = new ByteArrayOutputStream();  
thePic.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object   
byte[] byteArray = baos.toByteArray();

从像这样的字节数组中获取String

String imageString= Base64.encodeToString(byteArray , Base64.DEFAULT);

现在将此String保存在SharedPreference中,当您想要显示图像时,只需从SharedPreference获取此String并在ImageView中显示如下

byte[] imageBytes = Base64.decode(imageString.getBytes());
imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length));

答案 1 :(得分:0)

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;


public class FetchPath {
    /**
     * Get a file path from a Uri. This will get the the path for Storage Access
     * Framework Documents, as well as the _data field for the MediaStore and
     * other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri     The Uri to query.
     * @author paulburke
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

}

用法

Uri photoUri = data.getData();
 if (photoUri != null) {
 String filePath = FetchPath.getPath(this, photoUri);
  }