標籤:android style blog http color os io ar for
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 <ImageView13 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 block31 e.printStackTrace();32 }33 }34 }35 36 }37 }38 super.onActivityResult(requestCode, resultCode, data);39 }
Android調用系統相機擷取返回資料