一、使用摄像头拍照
新建一个空项目
day14_CameraAlbumTest
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/take_photo"
android:text="拍照"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/picture"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
如何实现调用摄像头:
- 创建一个
File
对象,存放摄像头拍下的图片 - 调用
getExternalCacheDir()
获取缓存目录,存放图片 - 接下来为了适配,如果Android版本低于7.0,直接将图片转化为
Uri对象
;否则调用getUriForFile()
转化为封装后的Uri对象
【用内容提供器】,参数一:context
,参数二:任意的唯一字符串,参数三:File对象 - 构建
Intent
对象,将其action
指定为android.media.action.IMAGE_CAPTURE
。用putExtra()
指定图片输出地址为Uri对象
- 最后调用
startActivityForResult()
隐式启动intent
,这样返回的图片会输出为图片文件 onActivityResult()
判断图片是否成功返回,如果成功,调用BitmapFactory.decodeStream()
将图片解析为Bitmap
对象,再显示出来
public class MainActivity extends AppCompatActivity {
private ImageView imageView_picture;
private Uri imageUri;
public static final int TAKE_PHOTO = 1;
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
imageView_picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else {
Toast.makeText(this, "未拍照", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_picture = findViewById(R.id.picture);
Button button_takePhoto = findViewById(R.id.take_photo);
button_takePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24) {
imageUri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".fileprovider", outputImage);
} else {
imageUri = Uri.fromFile(outputImage);
}
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
}
});
}
}
- 将第 3 步 用到的内容提供器添加注册,
android:name
属性值固定,android:authorities
和第二个参数一致,<meta-data>
指定Uri的共享路径,并引用了一个@xml/filepaths
资源
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.day14_cameraalbumtest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
......
<provider
android:authorities="com.example.day14_cameraalbumtest.fileprovider"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
</application>
</manifest>
- 第 7 步的文件还不存在,现在创建。在
res
目录新建一个xml
目录,下面新建file_path.xml
文件,然后修改其中内容,name
随便填,path
表示要共享的目录:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="my_images"
path="." />
</paths>
- 为了适配
Android 4.4
之前的手机,还要声明访问SD卡
的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
运行:
二、从相册选取照片
改布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/take_photo"
android:text="拍照"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/choose_photo"
android:text="选照片"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/picture"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
如何实现从相册选取图片:
- 运行时权限处理,申请
WRITE_EXTERNAL_STORAGE
这个危险权限,需要读写SD卡的能力 - 申请成功则继续构建
Intent对象
,指定action
:android.intent.action.GET_CONTENT
。用setType()
设置返回类型为图片 - 调用
startActivityForResult()
隐式启动intent
- 回调
onActivityResult()
判断图片是否成功返回,如果成功,对4.4以上系统采用handleImageOnKitkat()
,对4.4以下系统采用handleImageBeforeKitkat()
handleImageOnKitkat()
:- 返回的
uri
如果是document
类型,取出document id
处理获取路径图片- 如果
Uri
的authority
是media
格式的话,document id
还要再一步处理才能获取路径图片
- 如果
- 不是的话则普通方式处理,直接获得路径图片
- 返回的
public class MainActivity extends AppCompatActivity {
private ImageView imageView_picture;
private Uri imageUri;
public static final int TAKE_PHOTO = 1;
public static final int CHOOSE_PHOTO = 2;
private static final String TAG = "MainActivity";
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
imageView_picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "未拍照", Toast.LENGTH_SHORT).show();
}
break;
case CHOOSE_PHOTO:
if (resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= 19) {
handleImageOnKitkat(data);
} else {
handleImageBeforeKitkat(data);
}
} else {
Toast.makeText(this, "未选择图片", Toast.LENGTH_SHORT).show();
}
default:
break;
}
}
private void handleImageBeforeKitkat(Intent data) {
Uri uri = data.getData();
String imagePath = getImagePath(uri, null);
displayImage(imagePath);
}
@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];
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 displayImage(String imagePath) {
if (imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageView_picture.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "图片加载错误!", Toast.LENGTH_SHORT).show();
}
}
private String getImagePath(Uri externalContentUri, String selection) {
String path = null;
Cursor cursor = getContentResolver().query(externalContentUri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else {
Toast.makeText(this, "申请权限被拒绝", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_picture = findViewById(R.id.picture);
Button button_takePhoto = findViewById(R.id.take_photo);
button_takePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 24) {
imageUri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".fileprovider", outputImage);
} else {
imageUri = Uri.fromFile(outputImage);
}
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
}
});
Button button_choosePhoto = findViewById(R.id.choose_photo);
button_choosePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
openAlbum();
}
}
});
}
private void openAlbum() {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_PHOTO);
}
}
选取照片需要暂时豁免 Q 的外部存储沙箱限制,即在AndroidManifest.xml
中插入一句:
android:requestLegacyExternalStorage="true"
运行: