การใช้ Camera API ใน Flutter
ในบทความนี้ เราจะมาเรียนรู้วิธีการเข้าถึงและใช้งาน Camera API ใน Flutter เพื่อให้แอปพลิเคชันของเราสามารถถ่ายรูปและบันทึกวิดีโอได้ การใช้งาน Camera API เป็นฟีเจอร์ที่สำคัญสำหรับแอปพลิเคชันหลากหลายประเภท ไม่ว่าจะเป็นแอปพลิเคชันโซเชียลมีเดีย, แอปพลิเคชันอีคอมเมิร์ซ หรือแอปพลิเคชันที่ต้องการฟังก์ชันการทำงานด้านการถ่ายภาพและวิดีโอ
เตรียมตัวก่อนเริ่ม: Dependencies และ Permissions
ก่อนที่เราจะเริ่มเขียนโค้ด เราจำเป็นต้องติดตั้ง package ที่จำเป็นและขอ permission ในการเข้าถึงกล้องจากผู้ใช้
1. ติดตั้ง camera package
package camera เป็น package อย่างเป็นทางการจาก Flutter team ที่ช่วยให้เราสามารถเข้าถึงและควบคุมกล้องของอุปกรณ์ได้ เพิ่ม dependency นี้ลงในไฟล์ pubspec.yaml:
dependencies:
flutter:
sdk: flutter
camera: ^0.10.0
จากนั้นรันคำสั่ง flutter pub get เพื่อติดตั้ง package
2. ติดตั้ง image_picker package (ทางเลือก)
package image_picker ช่วยให้ผู้ใช้สามารถเลือกรูปภาพหรือวิดีโอจาก gallery ในเครื่องได้ หากต้องการใช้งาน ให้เพิ่ม dependency นี้ลงในไฟล์ pubspec.yaml:
dependencies:
flutter:
sdk: flutter
image_picker: ^0.9.0
จากนั้นรันคำสั่ง flutter pub get เพื่อติดตั้ง package
3. ขอ Permissions (Android และ iOS)
เพื่อให้แอปพลิเคชันสามารถเข้าถึงกล้องได้ เราต้องขอ permission จากผู้ใช้ โดยการเพิ่ม permission ที่เหมาะสมในไฟล์ AndroidManifest.xml (Android) และ Info.plist (iOS).
Android (android/app/src/main/AndroidManifest.xml):
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.your_app">
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<application
android:label="your_app"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
...
</application>
</manifest>
iOS (ios/Runner/Info.plist):
<key>NSCameraUsageDescription</key>
<string>This app needs camera access to take photos.</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app needs microphone access to record videos.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs access to your photo library to select images.</string>
คำอธิบาย:
NSCameraUsageDescription: ข้อความที่อธิบายว่าทำไมแอปพลิเคชันถึงต้องการเข้าถึงกล้องNSMicrophoneUsageDescription: ข้อความที่อธิบายว่าทำไมแอปพลิเคชันถึงต้องการเข้าถึงไมโครโฟน (สำหรับบันทึกวิดีโอ)NSPhotoLibraryUsageDescription: ข้อความที่อธิบายว่าทำไมแอปพลิเคชันถึงต้องการเข้าถึง photo library
ใช้งาน camera package
เมื่อเราติดตั้ง package และขอ permission เรียบร้อยแล้ว เราก็สามารถเริ่มใช้งาน Camera API ได้แล้ว
1. Initializing CameraController
CameraController เป็น class ที่ใช้ในการควบคุมกล้อง เราต้องสร้าง instance ของ CameraController และ initialize ก่อนใช้งาน
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
class CameraExample extends StatefulWidget {
@override
_CameraExampleState createState() => _CameraExampleState();
}
class _CameraExampleState extends State<CameraExample> {
late List<CameraDescription> cameras;
late CameraController controller;
@override
void initState() {
super.initState();
availableCameras().then((availableCameras) {
cameras = availableCameras;
if (cameras.isNotEmpty) {
controller = CameraController(cameras[0], ResolutionPreset.medium);
controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
});
} else {
print("No camera available");
}
}).catchError((error) {
print('Error: $error.code\nError Message: $error.message');
});
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (!controller.value.isInitialized) {
return Container(); // Or a loading indicator
}
return AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: CameraPreview(controller));
}
}
คำอธิบาย:
availableCameras(): ฟังก์ชันนี้จะคืนค่า List ของCameraDescriptionซึ่งเป็นข้อมูลเกี่ยวกับกล้องที่พร้อมใช้งานในอุปกรณ์CameraController(cameras[0], ResolutionPreset.medium): สร้าง instance ของCameraControllerโดยเลือกกล้องตัวแรกใน list (cameras[0]) และกำหนด resolution เป็นResolutionPreset.mediumcontroller.initialize(): InitializeCameraControllerซึ่งเป็น asynchronous operationCameraPreview(controller): Widget ที่แสดง preview ของกล้อง
2. ถ่ายรูป
เมื่อ CameraController ถูก initialize แล้ว เราสามารถใช้ฟังก์ชัน takePicture() เพื่อถ่ายรูปได้
Future<void> takePicture() async {
try {
final image = await controller.takePicture();
print('Image Path: ${image.path}');
// Do something with the image, e.g., display it or save it to storage
} catch (e) {
print(e);
}
}
คำอธิบาย:
controller.takePicture(): ฟังก์ชันนี้จะถ่ายรูปและคืนค่าXFileซึ่งมีข้อมูลเกี่ยวกับรูปภาพที่ถ่าย รวมถึง path ของไฟล์- เราสามารถนำ path ของไฟล์รูปภาพไปใช้เพื่อแสดงรูปภาพ หรือบันทึกลงใน storage ได้
3. บันทึกวิดีโอ
เราสามารถใช้ CameraController เพื่อบันทึกวิดีโอได้ โดยใช้ฟังก์ชัน startVideoRecording() และ stopVideoRecording()
Future<void> startVideoRecording() async {
try {
await controller.startVideoRecording();
} catch (e) {
print(e);
}
}
Future<void> stopVideoRecording() async {
try {
final video = await controller.stopVideoRecording();
print('Video Path: ${video.path}');
// Do something with the video, e.g., display it or save it to storage
} catch (e) {
print(e);
}
}
คำอธิบาย:
controller.startVideoRecording(): เริ่มการบันทึกวิดีโอcontroller.stopVideoRecording(): หยุดการบันทึกวิดีโอ และคืนค่าXFileซึ่งมีข้อมูลเกี่ยวกับวิดีโอที่บันทึก รวมถึง path ของไฟล์- เราสามารถนำ path ของไฟล์วิดีโอไปใช้เพื่อแสดงวิดีโอ หรือบันทึกลงใน storage ได้
ใช้งาน image_picker package
package image_picker ช่วยให้ผู้ใช้สามารถเลือกรูปภาพหรือวิดีโอจาก gallery ในเครื่องได้
1. เลือกรูปภาพจาก Gallery
import 'package:image_picker/image_picker.dart';
Future<void> pickImageFromGallery() async {
final ImagePicker _picker = ImagePicker();
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
if (image != null) {
print('Image Path: ${image.path}');
// Do something with the image, e.g., display it or save it to storage
} else {
print('No image selected.');
}
}
คำอธิบาย:
ImagePicker(): สร้าง instance ของImagePicker_picker.pickImage(source: ImageSource.gallery): เปิด gallery ให้ผู้ใช้เลือกรูปภาพ และคืนค่าXFileซึ่งมีข้อมูลเกี่ยวกับรูปภาพที่เลือก รวมถึง path ของไฟล์ImageSource.gallery: กำหนดให้เลือกรูปภาพจาก gallery
2. เลือกวิดีโอจาก Gallery
import 'package:image_picker/image_picker.dart';
Future<void> pickVideoFromGallery() async {
final ImagePicker _picker = ImagePicker();
final XFile? video = await _picker.pickVideo(source: ImageSource.gallery);
if (video != null) {
print('Video Path: ${video.path}');
// Do something with the video, e.g., display it or save it to storage
} else {
print('No video selected.');
}
}
คำอธิบาย:
ImagePicker(): สร้าง instance ของImagePicker_picker.pickVideo(source: ImageSource.gallery): เปิด gallery ให้ผู้ใช้เลือกวิดีโอ และคืนค่าXFileซึ่งมีข้อมูลเกี่ยวกับวิดีโอที่เลือก รวมถึง path ของไฟล์ImageSource.gallery: กำหนดให้เลือกวิดีโอจาก gallery
สรุป
ในบทความนี้ เราได้เรียนรู้วิธีการใช้งาน Camera API ใน Flutter โดยใช้ package camera และ image_picker เราได้เรียนรู้วิธีการ initialize CameraController, ถ่ายรูป, บันทึกวิดีโอ, และเลือกรูปภาพ/วิดีโอจาก gallery การใช้งาน Camera API เป็นฟีเจอร์ที่สำคัญสำหรับแอปพลิเคชันหลากหลายประเภท และเราหวังว่าบทความนี้จะเป็นประโยชน์สำหรับคุณ