android - 是否可以在没有预览和用户交互的情况下拍照?

标签 android flutter background camera flutter-packages

我需要在 flutter 中创建一个在线考试应用程序,我们需要每隔一段时间拍摄用户的照片和视频,并且在执行此操作时我们不想显示相机屏幕。

我尝试使用 flutter 的 Camera 插件,我可以拍照,但我找不到任何方法在没有相机预览的情况下捕捉图像

这是我的代码

import 'dart:async';
import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' show join;
import 'package:path_provider/path_provider.dart';
import 'package:countdown_flutter/countdown_flutter.dart';

Future<void> main() async {
 WidgetsFlutterBinding.ensureInitialized();

// Obtain a list of the available cameras on the device.
final cameras = await availableCameras();

// Get a specific camera from the list of available cameras.
 final firstCamera = cameras.first;
final frontCam = cameras[1];

runApp(
MaterialApp(
  theme: ThemeData.dark(),
  home: TakePictureScreen(
    // Pass the appropriate camera to the TakePictureScreen widget.
    camera: frontCam,
  ),
),
);
 }

  // A screen that allows users to take a picture using a given camera.
  class TakePictureScreen extends StatefulWidget {
  final CameraDescription camera;

  const TakePictureScreen({
   Key key,
   @required this.camera,
   }) : super(key: key);

   @override
  TakePictureScreenState createState() => TakePictureScreenState();
   }

  class TakePictureScreenState extends State<TakePictureScreen> {
  CameraController _controller;
   Future<void> _initializeControllerFuture;

   @override
   void initState() {
   super.initState();
   // To display the current output from the Camera,
  // create a CameraController.
_controller = CameraController(
  // Get a specific camera from the list of available cameras.
  widget.camera,
  // Define the resolution to use.
  ResolutionPreset.medium,
);

// Next, initialize the controller. This returns a Future.
_initializeControllerFuture = _controller.initialize();
 }

  @override
  void dispose() {
  // Dispose of the controller when the widget is disposed.
_controller.dispose();
super.dispose();
}

 @override
 Widget build(BuildContext context) {
 return Scaffold(
  appBar: AppBar(title: Text('Take a picture')),
  // Wait until the controller is initialized before displaying the
  // camera preview. Use a FutureBuilder to display a loading spinner
  // until the controller has finished initializing.

  body:
  FutureBuilder<void>(
    future: _initializeControllerFuture,
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.done) {
        // If the Future is complete, display the preview.
        return CameraPreview(_controller);
      } else {
        // Otherwise, display a loading indicator.
        return Center(child: CircularProgressIndicator());
      }
    },
  ),
  floatingActionButton: FloatingActionButton(
    child: Icon(Icons.camera_alt),
    // Provide an onPressed callback.
    onPressed: () async {
      // Take the Picture in a try / catch block. If anything goes wrong,
      // catch the error.
      try {
        // Ensure that the camera is initialized.
        await _initializeControllerFuture;
        // Construct the path where the image should be saved using the
        // pattern package.
        final path = join(
          // Store the picture in the temp directory.
          // Find the temp directory using the `path_provider` plugin.
          (await getTemporaryDirectory()).path,
          '${DateTime.now()}.png',
        );

        // Attempt to take a picture and log where it's been saved.
        await _controller.takePicture(path);

        // If the picture was taken, display it on a new screen.
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => DisplayPictureScreen(imagePath: path),
          ),
        );
      } catch (e) {
        // If an error occurs, log the error to the console.
        print(e);
      }
    },
  ),
);
 }
 }

 // A widget that displays the picture taken by the user.
 class DisplayPictureScreen extends StatelessWidget {
 final String imagePath ;

  const DisplayPictureScreen({Key key, this.imagePath}) : super(key: key);

  @override
  Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(title: Text('Display the Picture')),
  // The image is stored as a file on the device. Use the `Image.file`
  // constructor with the given path to display the image.
  body:
  Image.file(File(imagePath)),
);
}
 }

我不想显示预览屏幕,但偶尔会拍摄图像或视频。

最佳答案

  import 'package:camera/camera.dart';
  Future<String?> takePic() async {
    final camera = (await availableCameras()).first;
    final controller = CameraController( camera, ResolutionPreset.low );
    try {
      await controller.initialize();
      await controller.setFlashMode(FlashMode.off);
      final image = await controller.takePicture();
      controller.dispose();
      return image.path;
    }
    catch (e) { 
      // print(e);
      controller.dispose();
      return null;
    }

将第三行更改为类似 (await availableCameras())[1] 的内容以使用另一个相机。

关于android - 是否可以在没有预览和用户交互的情况下拍照?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65608497/

相关文章:

flutter - 如何在 Flutter 的 initState 中获取当前的 App Locale?

java - 当我使用类的方法时会发生崩溃代码吗?

java - onActivityResult 将数据从 fragment 返回到 Activity

android - 应用插件失败 [id 'com.android.internal.version-check' ]

linux - bash 启动额外的、虚假的后台进程

css - 背景幻灯片,但文本滚动

html - 在 IE8 中,当高度高于窗口时,ms-filter 背景消失。 (当出现滚动条时)

android - 以编程方式连接到蓝牙设备

在没有应用程序源代码的情况下使用 espresso 进行 Android 自动化

android - 尝试运行Flutter应用程序时,build.gradle文件中存在错误