码迷,mamicode.com
首页 > 其他好文 > 详细

使用相机和图库

时间:2014-05-21 19:50:06      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:android   c   code   tar   ext   a   

1、不用权限

2、启动照相机和图库

static final int TAKE_AVATAR_CAMERA_REQUEST = 1;//图库
static final int TAKE_AVATAR_GALLERY_REQUEST = 2;//照相机

//启动照相机

String strAvatarPrompt = "照个照片!";
Intent pictureIntent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Intent.createChooser(pictureIntent, strAvatarPrompt),
TAKE_AVATAR_CAMERA_REQUEST);//启动照相机

 

//启动图库

Intent pickPhoto=new Intent(Intent.ACTION_PICK);
pickPhoto.setType("image/*");
startActivityForResult(pickPhoto, TAKE_AVATAR_GALLERY_REQUEST);//启动图库选照片

 

//在onActivityResult获得返回的照片

protected void onActivityResult(int requestCode,int resultCode,Intent data) {
int maxLength=150;
switch (requestCode) {
case TAKE_AVATAR_CAMERA_REQUEST://照相机
if(resultCode==Activity.RESULT_OK){
Bitmap cameraPic=(Bitmap)data.getExtras().get("data");//取得照片
saveBitmap(cameraPic);//保存照片到应用程序
}else if(resultCode==Activity.RESULT_CANCELED)
break;
case TAKE_AVATAR_GALLERY_REQUEST://图库
if(resultCode==Activity.RESULT_OK){
Uri photoUri=data.getData();//取得照片
try {
Bitmap galleryPic=android.provider.MediaStore.Images.Media.getBitmap(getContentResolver(), photoUri);
saveBitmap(galleryPic);//保存照片到应用程序
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(resultCode==Activity.RESULT_CANCELED)
break;
default:
break;
}
}

//保存图片到应用程序

private void saveBitmap(Bitmap avatar) {
String strAvatarFilename = "avatar.jpg";
try {
avatar.compress(CompressFormat.JPEG, 100,
openFileOutput(strAvatarFilename, MODE_PRIVATE));
} catch (Exception e) {
Log.e(DEBUG_TAG, "Avatar compression and save failed.", e);
}

Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(
QuizSettingsActivity.this.getFilesDir(), strAvatarFilename));

// Update the settings screen
ImageButton avatarButton = (ImageButton) findViewById(R.id.ImageButton_Avatar);
String strAvatarUri = imageUriToSaveCameraImageTo.getPath();//取得图片的Uri
Uri imageUri = Uri.parse(strAvatarUri);
avatarButton.setImageURI(null); // Workaround for refreshing an
// ImageButton, which tries to cache the
// previous image Uri. Passing null
// effectively resets it.
avatarButton.setImageURI(imageUri);
}

 

使用相机和图库,布布扣,bubuko.com

使用相机和图库

标签:android   c   code   tar   ext   a   

原文地址:http://www.cnblogs.com/wdc224/p/3740081.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!