11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Flutter/ Dart】カメラで撮影した画像を圧縮する方法

Last updated at Posted at 2020-07-04

概要

カメラで撮影した画像をアップロードしたり、画面上に表示したりするアプリを開発しているときに、端末によってはカメラの解像度が高く(画像サイズが大きく)動作がもたつくのでアプリ内で圧縮してから扱う方法を模索しました。

結論

image_pickerを使えば簡単に実装できます!

設定

pubspec.yaml
dependencies:
  image_picker: [version]

アプリケーションコード

.dart
import 'package:image_picker/image_picker.dart';

で、インポートして、

.dart
final ImagePicker picker = ImagePicker();
final pickedFile = await picker.getImage(source: ImageSource.camera, imageQuality: 80);

これだけで実装できてしまいます!
imageQualityの値を低くすると圧縮率が上がります。

上記のコードに続けて、下記のように書いてあげると、dart.io.Fileを生成することができます。

.dart
final image = File(pickedFile.path);

なお、ImagePicker().getImageのシグネチャは以下のようになっており、画像の上限幅・高さの指定やカメラの指定(背面/ 前面)もできます。

.dart
  Future<PickedFile> getImage({
    @required ImageSource source,
    double maxWidth,
    double maxHeight,
    int imageQuality,
    CameraDevice preferredCameraDevice = CameraDevice.rear,
  }) {
    // 略
  }

他の方法

flutter_image_compressでも画像の圧縮が可能です。

設定

pubspec.yaml
dependencies:
  flutter_image_compress: [version]

アプリケーションコード

.dart
import 'package:flutter_image_compress/flutter_image_compress.dart';

で、インポートして、

.dart
Future<File> compressFile(File file) async {
  var result = await FlutterImageCompress.compressAndGetFile(
    file.absolute.path,
    file.absolute.path,
    quality: 80,
  );

  return result;
}

こんな感じでも実装できます!

11
5
1

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
11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?