天天看點

Android 調用系統攝像頭拍照儲存并且更新到圖庫

首先要添權重限
<!-- 在SDCard中建立與删除檔案權限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <!-- 往SDCard寫入資料權限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
           
調用攝像頭拍照
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 1);
           
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        //之是以用switch是因為使用者可能還需要選擇本地圖檔功能,我這裡沒有
        switch (requestCode) {
        case :
            Bundle bundle = data.getExtras();
            bitmap = (Bitmap) bundle.get("data");// 擷取相機傳回的資料,并轉換為Bitmap圖檔格式
            saveImageToGallery(this, bitmap);//存儲
            sign();
            try {
                view.setImageBitmap(bitmap);// 将圖檔顯示在ImageView裡
            } catch (Exception e) {
                System.out.println("請拍照");
            } 
            break;
        default:
            break;
        }
    }
           
public static void saveImageToGallery(Context context, Bitmap bitmap) {
        File appDir = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath(), "image");
        if (!appDir.exists()) {
            // 目錄不存在 則建立
            appDir.mkdirs();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(CompressFormat.JPEG, , fos); // 儲存bitmap至本地
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            ScannerByReceiver(context, file.getAbsolutePath());

            if (!bitmap.isRecycled()) {
                // bitmap.recycle(); 當存儲大圖檔時,為避免出現OOM ,及時回收Bitmap
                System.gc(); // 通知系統回收
            }
            // Toast.makeText(context, "圖檔儲存成功" ,
            // Toast.LENGTH_SHORT).show();
        }
    }

    /** Receiver掃描更新圖庫圖檔 **/

    private static void ScannerByReceiver(Context context, String path) {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://" + path)));
    }