Develop/Flutter

[Flutter] 플러터 image_picker 패키지를 통해 카메라 구현

JunJangE 2022. 1. 16. 17:17

이번에는 Flutter에서 카메라를 구현해보려고 했다.

카메라 구현을 위해 여러 패키지를 알아보았지만 UI 커스터마이징은 불가능한 것으로 보였고 다른 분들에 오픈 소스 코드도 확인해보았지만 앱을 재실행 시 카메라 구현이 안 되는 버그가 있어 보였다.

그중에서 image_picker 패키지는 다른 패키지보다 비교적 구현이 쉬웠고 버그도 없는 것으로 판단되어 image_picker 패키지를 통해 카메라를 구현해보려고 한다.

라이브러리

 

image_picker | Flutter Package

Flutter plugin for selecting images from the Android and iOS image library, and taking new pictures with the camera.

pub.dev

새 프로젝트를 생성하고 위 링크에 들어가 Installing의 다음 패키지를 pubspec.yaml에 추가한다.

dependencies:
  image_picker: ^0.8.4+4

다음으로 ios > Runner > info.plist에 들어가 다음 코드를 작성한다.

<key>NSCameraUsageDescription</key>
<string>Used to demonstrate image picker plugin</string>
<key>NSMicrophoneUsageDescription</key>
<string>Used to capture audio for image picker plugin</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Used to demonstrate image picker plugin</string>

Android의 경우 따로 설치할 필요 없이 실행 가능하다.

폴더는 위 이미지와 같이 구성되어 있다.

main.dart에서 앱을 생성하게 되고 camera_ex.dart에서 카메라를 구현하게 된다.

main.dart

import 'package:flutter/material.dart';
import 'camera_ex.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
      
        primarySwatch: Colors.green,
      ),
      home: CameraExample(),
    );
  }
}

camera_ex.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';

class CameraExample extends StatefulWidget {
  const CameraExample({Key? key}) : super(key: key);

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

class _CameraExampleState extends State<CameraExample> {
  File? _image;
  final picker = ImagePicker();

  // 비동기 처리를 통해 카메라와 갤러리에서 이미지를 가져온다.
  Future getImage(ImageSource imageSource) async {
    final image = await picker.pickImage(source: imageSource);

    setState(() {
      _image = File(image!.path); // 가져온 이미지를 _image에 저장
    });
  }

  // 이미지를 보여주는 위젯
  Widget showImage() {
    return Container(
        color: const Color(0xffd0cece),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.width,
        child: Center(
            child: _image == null
                ? Text('No image selected.')
                : Image.file(File(_image!.path))));
  }

  @override
  Widget build(BuildContext context) {
    // 화면 세로 고정
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);

    return Scaffold(
        backgroundColor: const Color(0xfff4f3f9),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(height: 25.0),
            showImage(),
            SizedBox(
              height: 50.0,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                // 카메라 촬영 버튼
                FloatingActionButton(
                  child: Icon(Icons.add_a_photo),
                  tooltip: 'pick Iamge',
                  onPressed: () {
                    getImage(ImageSource.camera);
                  },
                ),

                // 갤러리에서 이미지를 가져오는 버튼
                FloatingActionButton(
                  child: Icon(Icons.wallpaper),
                  tooltip: 'pick Iamge',
                  onPressed: () {
                    getImage(ImageSource.gallery);
                  },
                ),
              ],
            )
          ],
        ));
  }
}

위 코드를 보게 되면 정말 간단한 코드인 것을 확인할 수 있다.

image_picker 패키지를 통해 카메라와 갤러리의 이미지를 가져와 UI에 뿌려주게 되는 것이다.

코드를 다 작성한 후 실행하면 다음 영상과 같이 실행되는 것을 확인할 수 있다.

참고

 

완전 쉽고 간단한 Flutter 로 카메라 사용하기

어플에서 자주 쓰는 카메라 연동에 대해 알아볼 것이다. Dart 패키지에는 camera 관련 패키지가 있어 라이브러리를 가져와서 사용하면 된다. 아래의 단계별로 테스트를 진행해보겠다. 정말 별거 없

kyungsnim.net

 

image_picker | Flutter Package

Flutter plugin for selecting images from the Android and iOS image library, and taking new pictures with the camera.

pub.dev

github

 

GitHub - junjange/Flutter-Learning: 플러터 학습

플러터 학습. Contribute to junjange/Flutter-Learning development by creating an account on GitHub.

github.com