调用系统相机

来源:互联网 发布:部落冲突刷钻石软件 编辑:程序博客网 时间:2024/04/20 13:45
 Button image = (Button) findViewById(R.id.image);
        //调用照相机
        image.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 1);
            }

        });


@SuppressWarnings("deprecation")
    @SuppressLint("SdCardPath") @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        String sdStatus = Environment.getExternalStorageState();
        if(!sdStatus.equals(Environment.MEDIA_MOUNTED)){//检测sd卡是否可用
            Log.i("TestFile","SD card is not avaiable/writeable right now.");
            return ;
        }
        new DateFormat();
        //根据系统时间得到图片名
        String name = DateFormat.format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".jpg";
        System.out.println("图片名字====="+name);
        Bundle bundle = data.getExtras();
        //Bitmap是用于处理由像素数据定义的图像的对象。
        Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式
        FileOutputStream output = null;
        
        File file = new File("/sdcard/myimage/");
        file.mkdir(); //创建文件夹
        String fileName = "/sdcard/myimage/"+name;
        
        try {
            output = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);//把数据写进文件
            
        } catch (Exception e) {
            e.fillInStackTrace();
        }finally{
            try {
                output.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

}

0 0