1.获取系统相机权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
2.主函数
public class MainActivity extends AppCompatActivity {
private String s;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv=(ImageView)findViewById(R.id.iv);
}
public void cc(View ve){
switch (ve.getId()){
case R.id.but1:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
s = getExternalCacheDir().getAbsolutePath()+ File.separator+ "ab.png";
Uri uri = Uri.fromFile(new File(s));
intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
startActivityForResult(intent,100);
break;
case R.id.but2:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==100&&resultCode==RESULT_OK){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;
int outWidth = options.outWidth;
int outHeight = options.outHeight;
int ow=outWidth/200;
int oh=outHeight/200;
int max = Math.max(ow, oh);
options.inSampleSize=max;
options.inJustDecodeBounds=false;
Bitmap bitmap = BitmapFactory.decodeFile(s, options);
iv.setImageBitmap(bitmap);
}
}
}
3.主布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.myapplication.MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/but1"
android:text="相机"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="cc"/>
<Button
android:id="@+id/but2"
android:text="录像"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="cc"/>
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="300dp" />
</LinearLayout>