调用系统照相机

来源:互联网 发布:新手开淘宝网店 编辑:程序博客网 时间:2024/05/01 12:51
  1. public class MyCameraActivity extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.     private Button button;  
  4.   
  5.     @Override  
  6.     public void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.main);  
  9.         button = (Button) findViewById(R.id.button);  
  10.         button.setOnClickListener(new OnClickListener() {  
  11.   
  12.             @Override  
  13.             public void onClick(View v) {  
  14.                 // TODO Auto-generated method stub  
  15.                 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
  16.   
  17.                 startActivityForResult(intent, 1);  
  18.             }  
  19.         });  
  20.     }  
  21.   
  22.     @Override  
  23.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  24.         // TODO Auto-generated method stub  
  25.         super.onActivityResult(requestCode, resultCode, data);  
  26.         if (resultCode == Activity.RESULT_OK) {  
  27.             String sdStatus = Environment.getExternalStorageState();  
  28.             if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用  
  29.                 Log.i("TestFile",  
  30.                         "SD card is not avaiable/writeable right now.");  
  31.                 return;  
  32.             }  
  33.             String name = new DateFormat().format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".jpg";     
  34.             Toast.makeText(this, name, Toast.LENGTH_LONG).show();  
  35.             Bundle bundle = data.getExtras();  
  36.             Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式  
  37.           
  38.             FileOutputStream b = null;  
  39.            //???????????????????????????????为什么不能直接保存在系统相册位置呢????????????  
  40.             File file = new File("/sdcard/myImage/");  
  41.             file.mkdirs();// 创建文件夹  
  42.             String fileName = "/sdcard/myImage/"+name;  
  43.   
  44.             try {  
  45.                 b = new FileOutputStream(fileName);  
  46.                 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件  
  47.             } catch (FileNotFoundException e) {  
  48.                 e.printStackTrace();  
  49.             } finally {  
  50.                 try {  
  51.                     b.flush();  
  52.                     b.close();  
  53.                 } catch (IOException e) {  
  54.                     e.printStackTrace();  
  55.                 }  
  56.             }  
  57.             ((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);// 将图片显示在ImageView里  
  58.         }  
  59.     }  
  60. }  
原创粉丝点击