使用相机和图库

mac2022-06-30  25

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); }

 

转载于:https://www.cnblogs.com/wdc224/p/3740081.html

相关资源:webview 调用手机相机和图库demo
最新回复(0)