您的位置:首页 > 移动开发 > Android开发

Android调用系统相册和相机拍照

2017-12-07 09:25 381 查看
打算把最近项目中用到的知识点记录下来,顺便加深下记忆。相信很多软件都有这样的需求,需要调用手机的相册来选取图片,或者调用相机拍照。废话不多说,直接上代码。

一.调用系统相册

1.首先需要先添加权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


当然在android6.0之后,我们还需要在代码中动态添加权限,询问用户是否同意授权,这个在后面说。


2.调用相册并返回选择的图片

Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,0);


3.重写onActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0 && resultCode == Activity.RESULT_OK && data != null){
Uri uri = data.getData();
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(uri, filePathColumns, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePathColumns[0]);
String imagePath = c.getString(columnIndex);
Bitmap bm = BitmapFactory.decodeFile(imagePath);
img.setImageBitmap(bm);
c.close();
}
}


4.动态获取权限

在6.0之后,我们必须要在代码中动态的获取权限

if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED )
{
//权限还没有授予,需要在这里写申请权限的代码
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
GET_PERMISSION_REQUEST);
}else {
//权限已授予,执行

}


二.调用相机拍照并返回图片

1.添加权限

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission<
4000
/span> android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


2.调用相机拍照

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //系统常量, 启动相机的关键
startActivityForResult(intent, 1); // 参数常量为自定义的request code, 在取返回结果时有用


3.重写onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null){
String sdState= Environment.getExternalStorageState();
if(!sdState.equals(Environment.MEDIA_MOUNTED)){
return;
}
new android.text.format.DateFormat();
String name= android.text.format.DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))+".jpg";
Bundle bundle = data.getExtras();
//获取相机返回的数据,并转换为图片格式
Bitmap bitmap = (Bitmap)bundle.get("data");
FileOutputStream fout = null;
File file = new File("/sdcard/pintu/");
file.mkdirs();
String filename=file.getPath()+name;
try {
fout = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);//图像压缩
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
if(fout!=null){
try {
fout.flush();
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//插入图片
img.setImageBitmap(bitmap);

}
}


4.动态添加权限

if(ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},
GET_PERMISSION_REQUEST);
}else {

}


下面是全部代码:

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" >
<Button
android:id="@+id/btn_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="调用相册"/>
<Button
android:id="@+id/btn_camera"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="调用相机"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/img"/>
</LinearLayout>


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="camera.com.camerademo">

<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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

</manifest>


MainActivity.java

public class MainActivity extends AppCompatActivity {
private Button mPhoto;
private ImageView img;
private Button mCamera;
private final int GET_PERMISSION_REQUEST = 100; //权限申请自定义码

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCamera = (Button) findViewById(R.id.btn_camera);
mPhoto = (Button) findViewById(R.id.btn_photo);
img = (ImageView) findViewById(R.id.img);
mPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getPhoto();
}
});
mCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getCamera();
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0 && resultCode == Activity.RESULT_OK && data != null){
Uri uri = data.getData();
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(uri, filePathColumns, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePathColumns[0]);
String imagePath = c.getString(columnIndex);
Bitmap bm = BitmapFactory.decodeFile(imagePath);
img.setImageBitmap(bm);
c.close();
}else if(requestCode == 1 && resultCode == RESULT_OK && data != null){
String sdState= Environment.getExternalStorageState();
if(!sdState.equals(Environment.MEDIA_MOUNTED)){
return;
}
new android.text.format.DateFormat();
String name= android.text.format.DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))+".jpg";
Bundle bundle = data.getExtras();
//获取相机返回的数据,并转换为图片格式
Bitmap bitmap = (Bitmap)bundle.get("data");
FileOutputStream fout = null;
File file = new File("/sdcard/pintu/");
file.mkdirs();
String filename=file.getPath()+name;
try {
fout = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);//图像压缩
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
if(fout!=null){
try {
fout.flush();
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//插入图片
img.setImageBitmap(bitmap);

}
}
//调用相册权限
private void getPhoto(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED )
{
//权限还没有授予,需要在这里写申请权限的代码
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
GET_PERMISSION_REQUEST);
}else {
//权限已授予,执行
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent,0);
}
}
//调用相机权限
private void
908b
getCamera(){
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},
GET_PERMISSION_REQUEST);
}else {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //系统常量, 启动相机的关键
startActivityForResult(intent, 1); // 参数常量为自定义的request code, 在取返回结果时有用
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐