首先是布局
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="拍照"/>
<ImageView
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
然后修改主活动:
先是三个变量:
//调用摄像头
public static final int TAKE_PHOTO = 1;
private ImageView imageView_photo;
private Uri uri_photo;
修改主活动
//调用摄像头
//初始化调用摄像头要用的对象
imageView_photo = findViewById(R.id.picture);
Button button02 = findViewById(R.id.take_photo);
button02.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File outputImage = new File(getExternalCacheDir(), "output_image.jpg"); //储存拍摄的照片
if(outputImage.exists()) // 这个文件是否为空,不为空就删掉,
{
outputImage.delete();
}
try {
boolean create = outputImage.createNewFile(); //创建一个新文件
} catch (IOException e) {
e.printStackTrace();
}
if(Build.VERSION.SDK_INT >= 24)
{
uri_photo = FileProvider.getUriForFile(EightActivity.this, "com.example.myapplication.fileprovider", outputImage);
}else {
uri_photo = Uri.fromFile(outputImage);
}
//启动相机程序
Intent intent_for_open_photo = new Intent("android.media.action.IMAGE_CAPTURE"); //相机
intent_for_open_photo.putExtra(MediaStore.EXTRA_OUTPUT, uri_photo);
startActivityForResult(intent_for_open_photo, TAKE_PHOTO);
}
});
}
//拍照
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PHOTO: {
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri_photo));
imageView_photo.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
break;
default:
break;
}}
再src下新建一个文件夹,叫做xml,然后新建一个xml文件,命名 file_paths
内容:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-cache-path
name="my_images"
path="./" />
</paths>
然后在AndroidManiFest.xml中添加权限和一个提供器申明:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!--访问SD卡-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.myapplication.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
从相册选择照片
按钮
<Button
android:id="@+id/choose_from_album"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="从相册里选择一张照片"/>
主活动添加一个变量
public static final int CHOOSE_PHOTO = 2;
按钮事件
//选择照片
Button button03 = (Button)findViewById(R.id.choose_from_album);
button03.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(ContextCompat.checkSelfPermission(EightActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(EightActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}else{
openAlbun();
}
}
});
onActivityResult方法添加:
case CHOOSE_PHOTO: {
if (resultCode == RESULT_OK) {
//判断手机版本号
if (Build.VERSION.SDK_INT >= 19) {
//4.4以上使用这个
handleImageOnKitKat(data); //data是一个Intent,要重写这个方法
} else {
handleImageBeforeKitKat(data);
}
}
}
一些其他函数
//读取相册
//封装的打开相册的方法
private void openAlbun()
{
Intent intent_open_albun = new Intent("android.intent.action.GET_CONTENT");
intent_open_albun.setType("image/*");
startActivityForResult(intent_open_albun, CHOOSE_PHOTO);
}
@TargetApi(19)
private void handleImageOnKitKat(Intent data)
{
String imagePath = null;
Uri uri = data.getData();
if(DocumentsContract.isDocumentUri(this, uri))
{
String docId = DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority()))
{
String id = docId.split("1")[1]; //解析出数字格式的id
String selection = MediaStore.Images.Media._ID + "=" +id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
}
else if("com.android.providers.downloads.documents".equals(uri.getAuthority()))
{
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri, null);
}
}
else if("content".equalsIgnoreCase(uri.getScheme()))
{
imagePath = getImagePath(uri, null);
}
else if("file".equalsIgnoreCase(uri.getScheme()))
{
imagePath = uri.getPath();
}
displayImage(imagePath);
}
private void handleImageBeforeKitKat(Intent data)
{
Uri uri = data.getData();
String imagepath = getImagePath(uri, null);
displayImage(imagepath);
}
//为了调用相册,还要写这两个辅助方法
private String getImagePath(Uri uri, String selection)
{
String path = null;
//通过uri和selection获取真实的图片路径
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if(cursor != null)
{
if(cursor.moveToFirst())
{
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
private void displayImage(String imagePath)
{
if(imagePath != null)
{
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageView_photo.setImageBitmap(bitmap);
}else {
Toast.makeText(this, "获取图形失败", Toast.LENGTH_LONG).show();
}
}