Android调用系统相机获取返回数据

Android调用系统相机获取返回数据

由于项目需要调用相机,实现上传照片,例如微博,微信中功能。Android中可以非常轻松的调用系统相机,并返回Bitmap数据,但有一点不足,它返回的Bitmap尺寸很小,清晰度不够,这问题将稍后解决。下面通过代码演示。

1.界面布局

res/layout 定义一个简单布局,一个Button和ImageView,分别用于跳转系统相机Activity和显示系统相机返回数据。

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical" >
 6 
 7   <Button
 8         android:id="@+id/cap"
 9         android:layout_width="fill_parent"
10         android:layout_height="wrap_content"
11         android:text="摄像" />
12   <ImageView
13         android:id="@+id/image"
14         android:layout_width="fill_parent"
15         android:layout_height="fill_parent"
16         />
17 </Linea

2.Intent实现跳转系统相机

Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);

3.覆写onActivityResult方法

该方法用于接收系统相机返回数据,并显示图片

 1  @Override
 2     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 3         if(requestCode==1){
 4             if(resultCode==RESULT_OK){
 5             Bitmap bitmap=(Bitmap) data.getExtras().get("data");
 6             image.setImageBitmap(bitmap);
 7             SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS");
 8             String dir=Environment.getExternalStorageDirectory().getAbsolutePath()+
 9                       File.separator + "Cap";
10             String path=dir+File.separator+sdf.format(new Date())+".JPEG";
11             File directionary=new File(dir);
12             if(!directionary.exists()){
13                 directionary.mkdir();
14             }
15             File pic=new File(path);
16             FileOutputStream fos=null;
17             try {
18                 fos=new FileOutputStream(pic);
19                 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
20                 bitmap.compress(CompressFormat.JPEG,100, fos);
21                 Toast.makeText(getApplicationContext(), "照片生成\n"+path, Toast.LENGTH_LONG).show();
22             } catch (FileNotFoundException e) {
23                 
24                 e.printStackTrace();
25             }finally{
26                 if(fos!=null){
27                     try {
28                         fos.close();
29                     } catch (IOException e) {
30                         // TODO Auto-generated catch block
31                         e.printStackTrace();
32                     }
33                 }
34             }
35             
36             }
37         }
38         super.onActivityResult(requestCode, resultCode, data);
39     }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。