2014-03-05 114 views
0

我正在做一個用戶選擇圖像的項目,我們必須存儲圖像的路徑。我可以在imageView中顯示圖片,但是當應用程序關閉或用戶按下後退按鈕圖像時不顯示。所以我必須永遠保存圖像直到用戶刪除圖像。如何檢索存儲在數據庫中的圖像路徑並在圖像視圖中顯示?

以下是我的代碼:

Button buttonLoadImage = (Button) findViewById(R.id.pre1); 
     buttonLoadImage.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 

       Intent i = new Intent(
         Intent.ACTION_PICK, 
         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

       startActivityForResult(i, RESULT_LOAD_IMAGE); 
      } 
     }); 
    } 


    @SuppressWarnings("unused") 
    @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) { 
      Uri selectedImage = data.getData(); 
      String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

      Cursor cursor = getContentResolver().query(selectedImage, 
        filePathColumn, null, null, null); 
      cursor.moveToFirst(); 

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      String picturePath = cursor.getString(columnIndex); 
      cursor.close(); 

      Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath); 

      //testimage.setImageBitmap(yourSelectedImage); 
      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
      yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream); 
      byte[] byteArray = stream.toByteArray(); 

      ImageView imageView = (ImageView) findViewById(R.id.im2); 
      imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); 

      pd.open(); 
      pd.insert(picturePath); 
      pd.close(); 
     } 
    } 
+0

您可以將imagePath存儲在某處,如sqlite Db或sharedpref或文件系統 –

回答

0

看看你可以做兩件事情: -

  1. 如果你想圖像應保持其原來的地方,那麼你只能用它的路徑,將路徑保存到某個地方,如sharedPreference,fileSystem,sqlite數據庫或任何變種。
  2. 您可以在圖像複製到您的應用程序文件的另一種方式,那麼你可以使用像

,如果您有圖像的路徑,你可以得到圖像等爲: -

private void loadImageFromStorage(String path) 
    { 

     try { 

// if you want to use the same path then use this 
Bitmap b = BitmapFactory.decodeFile(pathName); 
       ImageView img=(ImageView)findViewById(R.id.imgPicker); 
      img.setImageBitmap(b); 
     } 
     catch (FileNotFoundException e) 
     { 
      e.printStackTrace(); 
     } 

    } 

不要」 t忘記授予權限<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

+0

我正在將路徑存儲在sqlite數據庫中......現在,如何在用戶回來時再次顯示它.. – user3304617

+0

我更新了我的答案,請檢查 –

+0

什麼是profile.jpg ...我們如何得到圖片的名稱? – user3304617

1

通常,當您想要將圖像保存到數據庫中時,它有很多種方法來存儲它。

1)您可以將圖像作爲imageName保存在數據庫中。

2)您還可以保存圖像的路徑到數據庫中,當你從數據庫中檢索該路徑字符串後,你可以解碼該路徑通常,當我們從庫獲取我們能做到。

3)您可以將圖像保存爲數據庫中的字節[],並且當您想要檢索它時,可以將其檢索爲BLOB圖像,然後將該字節[]轉換爲位圖並將該位圖設置爲ImageView 。

相關問題