はじめに
みんな大好き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;
    }
  }
}
