颤振:-用相机拍照 [英] Flutter :- Taking picture with camera

查看:98
本文介绍了颤振:-用相机拍照的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Flutter的新手,并编写了以下代码以在图像上显示捕获的图像.但是,相机预览未在我的手机上显示,Circular Indicator一直在旋转.我无法查看相机.

I am new to Flutter and have written the following code for showing captured image on a Image.However, the camera preview does not show on my phone and Circular Indicator keeps rotating. I am unable to view the Camera.

import 'dart:io';

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

class CameraDemo extends StatefulWidget {
  @override
  _CameraDemoState createState() => _CameraDemoState();
}

class _CameraDemoState extends State<CameraDemo> {
  CameraController _control;
  Future<void> _future;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _initApp();
  }

  void _initApp() async
  {
    WidgetsFlutterBinding.ensureInitialized();
    final cameras = await availableCameras();
    final firstCam = cameras.first;

    _control = CameraController(
      firstCam,
      ResolutionPreset.high,
    );

    _future = _control.initialize();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _control.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Save Picture")),
      body: FutureBuilder<void>(
        future: _future,
        builder: (context, snapshot) {
        if(snapshot.connectionState==ConnectionState.done)
          return CameraPreview(_control);
        else
          return Center(child: CircularProgressIndicator(),);

        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.camera_alt),
        onPressed: () async {
          try {
            await _future;

            final path = join(
              (await getTemporaryDirectory()).path,
              '${DateTime.now()}.png',
            );

            await _control.takePicture(path);
            Navigator.push(context, MaterialPageRoute(
                builder: (context){
                  return DisplayPicture(imagepath:path);
                },
            ));
          } catch (e) {
            print(e);
          }
        },
      ),
    );
  }


  }

  class DisplayPicture extends StatelessWidget {
  String imagepath;
  DisplayPicture({this.imagepath});

  @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)),
      );
    }
  }

推荐答案

您需要使用 image_picker 库从相机和图库中获取图像,请检查下面的代码用于相机和画廊.

You need to use the image_picker library for taking the image from the camera and gallery, Please check the below code i have used it for the camera and gallery.

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image_picker/image_picker.dart';

class HomeScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _HomeScreen();
  }
}

class _HomeScreen extends State<HomeScreen> {
  File imageFile = null;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blue,
          title: Text(
            "HomeScreen",
            textAlign: TextAlign.center,
          ),
        ),
        body: SafeArea(
          top: true,
          bottom: true,
          child: Align(
            alignment: Alignment.center,
            child: Column(
              children: <Widget>[
                Container(
                    width: MediaQuery.of(context).size.width * 0.35,
                    height: MediaQuery.of(context).size.height * 0.2,
                    margin: EdgeInsets.only(top: 20),
                    decoration: BoxDecoration(
                        color: Colors.grey,
                        shape: BoxShape.circle,
                        image: DecorationImage(
                            image: imageFile == null
                                ? AssetImage('images/ic_business.png')
                                : FileImage(imageFile),
                            fit: BoxFit.cover))),
                SizedBox(
                  height: 10.0,
                ),
                RaisedButton(
                    onPressed: () {
                      _settingModalBottomSheet(context);
                    },
                    child: Text("Take Photo")),
              ],
            ),
          ),
        ));
  }

  //********************** IMAGE PICKER
  Future imageSelector(BuildContext context, String pickerType) async {
    switch (pickerType) {
      case "gallery":

        /// GALLERY IMAGE PICKER
        imageFile = await ImagePicker.pickImage(
            source: ImageSource.gallery, imageQuality: 90);
        break;

      case "camera": // CAMERA CAPTURE CODE
        imageFile = await ImagePicker.pickImage(
            source: ImageSource.camera, imageQuality: 90);
        break;
    }

    if (imageFile != null) {
      print("You selected  image : " + imageFile.path);
      setState(() {
        debugPrint("SELECTED IMAGE PICK   $imageFile");
      });
    } else {
      print("You have not taken image");
    }
  }

  // Image picker
  void _settingModalBottomSheet(context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext bc) {
          return Container(
            child: new Wrap(
              children: <Widget>[
                new ListTile(
                    title: new Text('Gallery'),
                    onTap: () => {
                          imageSelector(context, "gallery"),
                          Navigator.pop(context),
                        }),
                new ListTile(
                  title: new Text('Camera'),
                  onTap: () => {
                    imageSelector(context, "camera"),
                    Navigator.pop(context)
                  },
                ),
              ],
            ),
          );
        });
  }
}

在清单中,您需要像下面这样输入摄像机

Inside the manifest you need to do entry of camera for it like below

<uses-permission android:name="android.permission.CAMERA" />

还有另外一个我正在使用默认图像 ic_business.png ,您可以使用它并确保在 pubspec.yaml

And one more i am using the default image ic_business.png, you can use it your and make sure entry inside the pubspec.yaml

库链接为单击此处

然后将输出

And output will following

这篇关于颤振:-用相机拍照的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆