Android拍照或者从相册选取图片加载在imageview上
时间: 2024-02-22 16:55:55 浏览: 70
好的,以下是Android拍照或者从相册选取图片加载在imageview上的具体步骤:
1. 在AndroidManifest.xml文件中添加相机和存储权限:
```
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
2. 在布局文件中添加一个ImageView:
```
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
3. 在Activity中定义以下变量:
```
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int REQUEST_IMAGE_PICK = 2;
private ImageView imageView;
private Uri imageUri;
```
4. 在需要拍照或者从相册选取图片的地方,添加以下代码:
拍照:
```
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
imageUri = FileProvider.getUriForFile(this, "com.example.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
```
从相册选取图片:
```
Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhotoIntent, REQUEST_IMAGE_PICK);
```
5. 在Activity中添加以下方法:
```
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
imageView.setImageURI(imageUri);
} else if (requestCode == REQUEST_IMAGE_PICK) {
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
return imageFile;
}
```
以上就是Android拍照或者从相册选取图片加载在ImageView上的完整代码,希望可以帮助到你。
阅读全文