2015-10-16 68 views
0

我正在做一個應用程序來將圖片從圖庫保存到ImageView中,爲此我必須保存在sharedPreference中,以便當我離開應用程序並返回時,圖像仍然存在。如何將裁剪後的圖像URI保存在saredPreference中?

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 但沒有工作

也許我有位圖轉換爲字符串或做別的東西,但我不知道

Thakns反正

回答

0

您可以保存裁剪的圖像位圖SharedPreference。由於我們只能存儲布爾型,浮點型,中等,長,SharedPreference字符串值。但有一兩件事你可以做的是位圖轉換爲Base64字符串並保存在SharedPreference,然後檢索字符串時,以往用戶打開應用程序..

位圖轉換爲字節數組是這樣的:從字節

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); 

現在數組保存此字符串SharedPreference,當你要顯示的圖像只是得到SharedPreference這個字符串,並顯示在ImageView的這樣

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

感謝您的支持。我這樣做了,但是在我裁剪之後,圖像沒有出現在ImageView中。它全是白色的。可以是什麼? –

+0

@Mustanserlqbal –

+0

請分享您的代碼? –

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); 
    } 
+0

我不明白如何使用這個。你能解釋我嗎? –

+0

如果你可以@AnoopM –