- img=(ImageView)findViewById(R.id.img);
- take_picture=(Button)findViewById(R.id.take_picture);
- take_picture.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
- startActivityForResult(intent,Activity.DEFAULT_KEYS_DIALER);
- }
- });
- }
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (resultCode == Activity.RESULT_OK) {
- String sdStatus = Environment.getExternalStorageState();
- if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
- return;
- }
- Bundle bundle = data.getExtras();
- Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式
- FileOutputStream b = null;
- File file = new File("/sdcard/myImage/");
- file.mkdirs();// 创建文件夹,名称为myimage
- //照片的命名,目标文件夹下,以当前时间数字串为名称,即可确保每张照片名称不相同。
- String str=null;
- Date date=null;
- SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");//获取当前时间,进一步转化为字符串
- date =new Date();
- str=format.format(date);
- String fileName = "/sdcard/myImage/"+str+".jpg";
- try {
- b = new FileOutputStream(fileName);
- bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } finally {
- try {
- b.flush();
- b.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (data!= null) {
- Bitmap cameraBitmap = (Bitmap) data.getExtras().get("data");
- System.out.println("fdf================="+data.getDataString());
- img.setImageBitmap(cameraBitmap);
- System.out.println("成功======"+cameraBitmap.getWidth()+cameraBitmap.getHeight());
- }
- }
- }
- }
- }
来源: http://www.phpxs.com/code/1002833/