android獲取本地圖片或拍照圖片

 
從SD卡中獲取圖片資源,或者拍一張新的圖片。
先貼代碼
獲取圖片:
 
<EM><STRONG>    CharSequence[] items = { "相冊", "相機"};    
         new AlertDialog.Builder( this)
            .setTitle( "選擇圖片來源")
            .setItems(items, new OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
           if( which == SELECT_PICTURE ){
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType( "p_w_picpath/*");
            startActivityForResult(Intent.createChooser(intent, "選擇圖片"), SELECT_PICTURE);    
                     } else{
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);    
                        startActivityForResult(intent, SELECT_CAMER);    
                     }
        }
      })
      .create().show(); </STRONG></EM>

 
註釋:拍照獲取的話,能夠指定圖片的保存地址,在此不說明。
 
 
處理圖片,方法一,直接處理返回圖片:
<EM><STRONG><STRONG> protected void onActivityResult( int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
//選擇圖片
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
if(bmp != null) //若是不釋放的話,不斷取圖片,將會內存不夠
bmp.recycle();
bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( "the bmp toString: " + bmp);
p_w_picpathSV.setBmp(bmp);
} else{
Toast.makeText(SetImageActivity. this, "請從新選擇圖片", Toast.LENGTH_SHORT).show();
}

}</STRONG></STRONG></EM>
註釋:
一、網上有說明,直接處理返回的圖片是被系統壓縮過的,不過本身在測試的過程並無區別;
二、若是用戶不斷的從新獲取圖片的話,必須把如今的Bmp內存釋放,不然會報錯! bmp.recycle()。
 
 
處理圖片,方法二,得到圖片的地址再處理:
 
protected void onActivityResult( int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if(resultCode == RESULT_OK){
    Uri uri = data.getData();    
    String [] proj={MediaStore.Images.Media.DATA};
    Cursor cursor = managedQuery( uri,
        proj,                                 // Which columns to return
         null,             // WHERE clause; which rows to return (all rows)
         null,             // WHERE clause selection arguments (none)
         null);                                 // Order-by clause (ascending by name)
    
     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    
    String path = cursor.getString(column_index);
    bmp = BitmapFactory.decodeFile(path);
    System.out.println( "the path is :" + path);
  } else{
    Toast.makeText(SetImageActivity. this, "請從新選擇圖片", Toast.LENGTH_SHORT).show();   }      }
轉自:http://blog.csdn.net/you_and_me12/article/details/7262988
相關文章
相關標籤/搜索