2015-10-06 18 views
2

我是新來的Android編程。我想知道如何從圖庫中選擇圖像並將其作爲ImageView背景。 我讓代碼從圖庫中選擇並使其成爲ImageView背景,但每次離開應用程序時圖像都會消失。 我必須保存在數據庫中,但我沒有太多的知識吧如何從圖庫中選擇圖片,並保存爲背景的ImageView,使用SQLite

如果有人能幫助我.. 謝謝

我的Java文件

ImageView btn1, btn2; 
    Uri photoPath; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     btn1 = (ImageView) findViewById(R.id.imageView1); 


     btn1.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 


       Intent intent = new Intent(); 
       intent.setType("image/*"); 
       intent.setAction(Intent.ACTION_GET_CONTENT); 
       startActivityForResult(Intent.createChooser(intent, "Altere o botão"), 1); 
      } 
     }); 

} 

    public void onActivityResult(int reqCode, int resCode, Intent data){ 

     if(resCode == RESULT_OK){ 
      if(reqCode == 1){ 
       btn1.setImageURI(data.getData()); 
      } 
     } 
    } 

我的XML文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center" 
    tools:context="com.example.camera.MainActivity" > 

<ImageView 
    android:id="@+id/imageView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/ic_launcher" 
    /> 

</LinearLayout> 

回答

0

好的。看起來像您的代碼獲取圖像並將其設置爲Imageview工作正常。 我的建議是將圖像保存在本地文件夾中,而不是在Sqlite數據庫中,因爲它會使數據庫變得沉重。但是請將Uri或圖像的路徑保存在數據庫中。

使用下面的代碼將圖像保存在本地文件夾

private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) { 

File direct = new File(Environment.getExternalStorageDirectory() + "/DirName"); 

if (!direct.exists()) { 
    File wallpaperDirectory = new File("/sdcard/DirName/"); 
    wallpaperDirectory.mkdirs(); 
} 

File file = new File(new File("/sdcard/DirName/"), fileName); 
if (file.exists()) { 
    file.delete(); 
} 
try { 
    FileOutputStream out = new FileOutputStream(file); 
    imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out); 
    out.flush(); 
    out.close(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

}

這是一個簡單的教程SQLite數據庫 Sqlite Database tutorial

相關問題