|概要
目的/意义:这篇文章的目的在于避免新手入坑,大神可以点击X出去了,因为我刚好开始学安卓,所以我觉得有必要分享一下啦
开发环境:Android Studio
关键词:\
|正式内容
以下是郭霖大神的调取摄像头完成拍照功能的完整代码,可以拷贝
package com.example.administrator.demo;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class UserManagementActivity extends AppCompatActivity {
public static final int TAKE_PHOTO = 1;
private ImageView picture;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_management);
Button takePhoto = findViewById(R.id.take_photo);
picture = findViewById(R.id.picture);
takePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//创建File对象,用于存储拍照后的图片
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(UserManagementActivity.this,"com.example.administrator.demo.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);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){ switch (requestCode){
case TAKE_PHOTO:
if (resultCode == RESULT_OK){
try {
//将拍摄的照片显示出来
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e){
e.printStackTrace(); }
}
break;
default: break;
}
}}
我从文本里面复制出来粘贴在简书的编辑器后代码就成了这样,不要吐槽我代码风格不好
这里,一般新手都会添加一个权限打开,但是以上代码的实现是不需要打开android.permission.CAMERA该权限的
即意思是把android.permission.CAMERA注释掉了就可以运行成功
网友评论