2025-05-24

廢話不多說,直接進入主題,想要在android中實現拍照最簡單餓方法就是New 一個 Intent 設置Action為android.media.action.IMAGE_CAPTURE 然後使用startActivityForResult(intent,REQUEST_CODE)方法進入相機。當然還有很多方式可以實現,大傢可以在網上查找。但是要註意的是在進入相機前最好判斷下sdcard是否可用,代碼如下:
查看源碼
 
打印
1                destoryBimap();
2 String state = Environment.getExternalStorageState();
3 if (state.equals(Environment.MEDIA_MOUNTED)) {
4     intent = new Intent("android.media.action.IMAGE_CAPTURE");
5     startActivityForResult(intent, REQUEST_CODE);
6 } else {
7     Toast.makeText(DefectManagerActivity.this,
8             R.string.common_msg_nosdcard, Toast.LENGTH_LONG).show();
9 }
當拍照完成以後需要在onActivityResult(int requestCode, int resultCode, Intent data)方法中獲取拍攝的圖片,android把拍攝的圖片封裝到bundle中傳遞回來,但是根據不同的機器獲得相片的方式不太一樣,所以會出現某一種方式獲取圖片為null的想象,解決辦法就是做一個判斷,當一種方式不能獲取,就是用另一種方式,下面是分別獲取相片的兩種方式:
查看源碼
 
打印
01                Uri uri = data.getData();
02 if (uri != null) {
03     photo = BitmapFactory.decodeFile(uri.getPath());
04 }
05 if (photo == null) {
06     Bundle bundle = data.getExtras();
07     if (bundle != null) {
08         photo = (Bitmap) bundle.get("data");
09     } else {
10         Toast.makeText(DefectManagerActivity.this,
11                 getString(R.string.common_msg_get_photo_failure),
12                 Toast.LENGTH_LONG).show();
13         return;
14     }
15 }
第一種方式是用方法中傳回來的intent調用getData();方法獲取數據的Uri,然後再根據uri獲取數據的路徑,然後根據路徑封裝成一個bitmap就行瞭.
第二種方式也是用法中傳回來的intent對象但是不再是調用getData();方法而是調用getExtras();方法獲取intent裡面所有參數的一個對象集合bundle,然後是用bundle對象得到鍵為data的值也就是一個bitmap對象.
通過上面兩種方式就能獲取相片的bitmap對象,然後就可以在程序中是用,如果你想把相片保存到自己指定的目錄可以是用如下步驟即可:
首先bitmap有個一compress(Bitmap.CompressFormat.JPEG, 100, baos)方法,這個方法有三個參數,第一個是指定將要保存的圖片的格式,第二個是圖片保存的質量,值是0-100,比如像PNG格式的圖片這個參數你可以隨便設置,因為PNG是無損的格式。第三個參數是你一個緩沖輸出流ByteArrayOutputStream();,這個方法的作用就是把 bitmap的圖片轉換成jpge的格式放入輸出流中,然後大傢應該明白怎麼操作瞭吧,下面是實例代碼:
查看源碼
 
打印
01           String pictureDir = "";
02 FileOutputStream fos = null;
03 BufferedOutputStream bos = null;
04 ByteArrayOutputStream baos = null;
05 try {
06     baos = new ByteArrayOutputStream();
07     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
08     byte[] byteArray = baos.toByteArray();
09     String saveDir = Environment.getExternalStorageDirectory()
10             + "/temple";
11     File dir = new File(saveDir);
12     if (!dir.exists()) {
13         dir.mkdir();
14     }
15     File file = new File(saveDir, "temp.jpg");
16     file.delete();
17     if (!file.exists()) {
18         file.createNewFile();
19     }
20     fos = new FileOutputStream(file);
21     bos = new BufferedOutputStream(fos);
22     bos.write(byteArray);
23     pictureDir = file.getPath();
24 } catch (Exception e) {
25     e.printStackTrace();
26 } finally {
27     if (baos != null) {
28         try {
29             baos.close();
30         } catch (Exception e) {
31             e.printStackTrace();
32         }
33     }
34     if (bos != null) {
35         try {
36             bos.close();
37         } catch (Exception e) {
38             e.printStackTrace();
39         }
40     }
41     if (fos != null) {
42         try {
43             fos.close();
44         } catch (Exception e) {
45             e.printStackTrace();
46         }
47     }
48 }
然後就是實現圖片的上傳功能,我這裡是是用的apache的HttpClient裡面的MultipartEntity實現文件上傳具體代碼如下:
查看源碼
 
打印
01 /**
02      * 提交參數裡有文件的數據
03      * 
04      * @param url
05      *            服務器地址
06      * @param param
07      *            參數
08      * @return 服務器返回結果
09      * @throws Exception
10      */
11     public static String uploadSubmit(String url, Map<String, String> param,
12             File file) throws Exception {
13         HttpPost post = new HttpPost(url);
14  
15         MultipartEntity entity = new MultipartEntity();
16         if (param != null && !param.isEmpty()) {
17             for (Map.Entry<String, String> entry : param.entrySet()) {
18                 entity.addPart(entry.getKey(), new StringBody(entry.getValue()));
19             }
20         }
21         // 添加文件參數
22         if (file != null && file.exists()) {
23             entity.addPart("file", new FileBody(file));
24         }
25         post.setEntity(entity);
26         HttpResponse response = httpClient.execute(post);
27         int stateCode = response.getStatusLine().getStatusCode();
28         StringBuffer sb = new StringBuffer();
29         if (stateCode == HttpStatus.SC_OK) {
30             HttpEntity result = response.getEntity();
31             if (result != null) {
32                 InputStream is = result.getContent();
33                 BufferedReader br = new BufferedReader(
34                         new InputStreamReader(is));
35                 String tempLine;
36                 while ((tempLine = br.readLine()) != null) {
37                     sb.append(tempLine);
38                 }
39             }
40         }
41         post.abort();
42         return sb.toString();
43     }
這裡就基本上對圖片上傳就差不多瞭,但是還有一個問題就是圖片上傳完以後bitmap還在內存中,而且大傢都知道如果,高清的圖片比較大,而手機內存本來就有限,如果不進行處理很容易報內存溢出,所以我們應該把處理完的bitmap從內存中釋放掉,這時候就需要調用bitmap的recycle();方法,調用這個方法的時候需要註意不能太早也不能太晚,不然會報異常,一般可以放在下一張圖片生成前或者沒有任何view引用要銷毀的圖片的時候下面是實例代碼:
查看源碼
 
打印
1 /**
2      * 銷毀圖片文件
3      */
4     private void destoryBimap() {
5         if (photo != null && !photo.isRecycled()) {
6             photo.recycle();
7             photo = null;
8         }
9     }

 

摘自  采菊東籬下
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *