0
2

More than 3 years have passed since last update.

【Flutter】デバイスから画像や動画を取得(Image Picker)

Last updated at Posted at 2020-11-24

概要

パブリックへのアップロードを実装する際に、ローカルデバイスのギャラリーから画像や動画を取得し一旦保持する処理が必要になります。それを今回はプラグインとして提供されているImage Pickerで実装していきます。

手順

0.iOS用のセットアップ
info.plist
<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires to access your photo library</string>
<key>NSCameraUsageDescription</key>
<string>This app requires to add file to your camera</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app requires to add file to your photo library your microphone</string>
1.パッケージの導入

画像も動画もimage_pickerを使います。
以下のように、dependencies:の配下に記載しましょう。

pubspec.yaml
dependencies:
  image_picker: ^0.6.7+11
2.インポート
import 'dart:io';
import 'package:image_picker/image_picker.dart';
3.ファイルを取得

Stateクラスの中に定義します。

class _UploadScreenState extends State<UploadScreen> {
  File _video;
  final picker = ImagePicker();

  Future getVideoFromGalley() async {
//  画像の場合
//  final pickedFile = await picker.getImage(source: ImageSource.gallery);
    final pickedFile = await picker.getVideo(source: ImageSource.gallery);
    setState(() {
      if (pickedFile != null) {
        _video = File(pickedFile.path);
      } else {
        print('No video selected');
      }
    });
  }

上記はギャラリーから取得する場合。
カメラから取得したい場合は、source: ImageSource.cameraとしてください。
これで_videoに画像や動画の中身が格納されたのであとは煮るなり焼くなりしてください。

Tips

アップロード用ファイルをサイズで制限したい時、ファイルオブジェクトからサイズを取得できます。(バイト単位)


  _videoSize = _video.lengthSync();

メガバイト単位で少数第3位まで取得したい場合

  _videoSize = ((((_video.lengthSync()/1048576)*1000).round())/1000);

さいごに

お疲れ様でした!

参考サイト

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2