android调用系统相机拍照并保存本地

public class PhotographActivity extends AppCompatActivity {

    public static Handler handler ;
    private static String srcPath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photograph);
            Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(it, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            //获取系统时间
            Bundle extras = data.getExtras();
            Bitmap b = (Bitmap) extras.get("data");
            String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
            String fileNmae = Environment.getExternalStorageDirectory().toString()+File.separator+"OCR/image/"+name+".jpg";
            //拿到图片保存地址
            srcPath = fileNmae;
            Message msg = Message.obtain();
            msg.obj=srcPath;
            if (handler!=null){
                handler.sendMessage(msg);
            }
            File myCaptureFile =new File(fileNmae);
            try {
                if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                    if(!myCaptureFile.getParentFile().exists()){
                        myCaptureFile.getParentFile().mkdirs();
                    }
                    BufferedOutputStream bos;
                    bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                    b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                    bos.flush();
                    bos.close();
                }else{
                    Toast toast= Toast.makeText(this, "保存失败,SD卡无效", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        finish();
    }

}

猜你喜欢

转载自blog.csdn.net/weikai_/article/details/80347207