從SD卡中擷取圖片資源,或者拍一張新的圖片。
先貼代碼
擷取圖片:
注釋:拍照擷取的話,可以指定圖片的儲存地址,在此不說明。
複製代碼 代碼如下: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("image/*");
startActivityForResult(Intent.createChooser(intent, "選擇圖片"), SELECT_PICTURE);
}else{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, SELECT_CAMER);
}
}
})
.create().show();
處理圖片,方法一,直接處理返回圖片:
注釋:
1、網上有說明,直接處理返回的圖片是被系統壓縮過的,不過自己在測試的過程並沒有區別;
2、如果使用者不斷的重新擷取圖片的話,必須把現在的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();
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);
imageSV.setBmp(bmp);
}else{
Toast.makeText(SetImageActivity.this, "請重新選擇圖片", Toast.LENGTH_SHORT).show();
}
}
處理圖片,方法二,獲得圖片的地址再處理: 複製代碼 代碼如下: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();
}
}