android图像绘制(六)获取本地图片或拍照图片等图片资源
从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();
}
}