LoginSignup
2
3

More than 3 years have passed since last update.

Flutter image_pickerでpngを選択するとクラッシュする場合の対処法

Last updated at Posted at 2020-09-20

はじめに

みんな大好きimage_pickerのプラグイン

備忘録。

現象

Androidの場合に、

以下で選択したファイルがPNGの場合にクラッシュ。

var file = await ImagePicker().getImage(source: ImageSource.camera);

対策

FileクラスにExtensionを生やして、Jpegに変換して対応。

IOFileExtensions.dart
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:image/image.dart';

extension IOFileExtensions on File {
  Future<File> convertJpg({int resizeWidth = 500}) async {
    if (this == null) { return null; }
    try {
      final image = decodeImage(readAsBytesSync());
      final aspect = image.height / image.width;
      final thumbnail = copyResize(image, width: resizeWidth, height: resizeWidth * aspect.toInt());
      return await writeAsBytes(encodeJpg(thumbnail));
    }
    catch(error) {
      debugPrint('convert jpg error: ${error.toString()}');
      return this;
    }
  }
}
2
3
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
2
3