相机的简单使用
Posted 钱大少丶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了相机的简单使用相关的知识,希望对你有一定的参考价值。
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button button; private Button button2; private ImageView imageView; private String sdpath; private String picpath; private static int SLT=1;//请求缩略图的标识 private static int YT=2;//请求原图的标识 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sdpath= Environment.getExternalStorageDirectory().getPath(); picpath= sdpath+"/"+"temp.png"; initView(); } private void initView() { button = (Button) findViewById(R.id.button); button2 = (Button) findViewById(R.id.button2); imageView = (ImageView) findViewById(R.id.imageView); button.setOnClickListener(this); button2.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: // Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent,YT); break; case R.id.button2: Intent intent2=new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //定义一个路径 Uri uri=Uri.fromFile(new File(picpath)); //为拍照指定一个路径 intent2.putExtra(MediaStore.EXTRA_OUTPUT,uri); startActivityForResult(intent2,YT); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode==RESULT_OK){ if (requestCode==SLT){ //通过Bundle 取图片 Bundle extras = data.getExtras(); Bitmap bitmap = (Bitmap) extras.get("data"); imageView.setImageBitmap(bitmap); }else if (requestCode==YT){ FileInputStream fileInputStream=null; try { fileInputStream=new FileInputStream(picpath); //把流转化为BITMAP Bitmap bitmap= BitmapFactory.decodeStream(fileInputStream); imageView.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); }finally { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
记住添加权限
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
以上是关于相机的简单使用的主要内容,如果未能解决你的问题,请参考以下文章