1.调用系统摄像头
1.声明常量和变量
2.按钮点击事件,打开系统摄像头
3.重写onActivityResult事件接收拍照返回
4.生成文件名返回路径
5.保存图片
- private static final int TAKE_PICTURE = 1;
- class btnGotoActivity02Listener implements OnClickListener {
- public void onClick(View v) {
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用摄像头拍照
- startActivityForResult(intent, TAKE_PICTURE);
- }
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- String filename = "";
- try {
- if (resultCode == Activity.RESULT_OK && requestCode == TAKE_PICTURE) {
- Bundle bundle = data.getExtras();
- Bitmap bmp = (Bitmap)bundle.get("data");
- filename = saveImage(bmp);
- }
- } catch (Exception err) {
- Log.e("Exception", err.getLocalizedMessage());
- }
- }
- public String buildFileName(){
- Date now = new Date();
- SimpleDateFormat formater = new SimpleDateFormat("yyMMdd_HHmmss");
- String SDCARD = Environment.getExternalStorageDirectory() + "/";
- String basePath = SDCARD + "dier/photo/";
- File dir = new File(basePath);
- dir.mkdirs();
- return basePath + formater.format(now) + ".jpg";
- }
- public String saveImage(Bitmap bmp) throws Exception {
- File file = new File(buildFileName());
- file.createNewFile();
- FileOutputStream oStream = new FileOutputStream(file);
- bmp.compress(Bitmap.CompressFormat.JPEG, 100, oStream); //100是照片质量,0-100,越大越好
- oStream.flush();
- oStream.close();
- return file.getPath();
- }
2.保存完整分辨率的照片
使用上面的方法,保存下来的图片仅为原图的1/4大小,如果需要保存大照片则需要使用下面的方式
缺点:此方法除了在指定的目录下保存图片外,在系统拍照路径下也会保存下一张相同的图片。
- private static final int TAKE_PICTURE = 1;
- private String TEMP_FILE = "";
- class btnGotoActivity02Listener implements OnClickListener {
- public void onClick(View v) {
- TEMP_FILE = buildFileName();
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用摄像头拍照
- intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(TEMP_FILE))); //另存图片地址
- startActivityForResult(intent, TAKE_PICTURE);
- }
- }
- public String buildFileName(){
- Date now = new Date();
- SimpleDateFormat formater = new SimpleDateFormat("yyMMdd_HHmmss");
- String SDCARD = Environment.getExternalStorageDirectory() + "/";
- String basePath = SDCARD + "dier/photo/";
- File dir = new File(basePath);
- dir.mkdirs();
- return basePath + formater.format(now) + ".jpg";
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- String filename = "";
- try {
- if (resultCode == Activity.RESULT_OK && requestCode == TAKE_PICTURE) {
- File file = new File(TEMP_FILE);
- if(file.exists()){
- filename = file.getPath();
- Toast.makeText(MainActivity.this, "图片已保存在:" + filename, 3000).show();
- }
- else {
- Toast.makeText(MainActivity.this, "亲,我实在无能为力啊,你是用啥程序照的相片?", 5000).show();
- }
- }
- } catch (Exception err) {
- Log.e("Exception", err.getLocalizedMessage());
- }
- }