LoginSignup
8
8

More than 1 year has passed since last update.

Flutter画像の表示方法と各形式の変換

Last updated at Posted at 2022-07-21

Flutterにおいて、画像の表示方法は下記の通りです。

  1. Image.asset
  2. Image.network
  3. Image.file
  4. Image.memory

Image.asset

アプリ内(アセット)の画像を表示する方法です。pathはアセットのlocalパスです。

  1. プロジェクト直下にimagesフォルダを作成して、表示したい画像をその中に入れます。
  2. pubspec.yamlを編集する
  3. Image.assetで画像を表示する
flutter:
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - images/asset.jpg

Image.network

ネットから画像を表示する方法です。pathは画像のネットワークURLです。

return SizedBox(
      height: 60,
      width: 60,
      child: Image.network(
        "https://XXXXXXXXXX",
        fit: BoxFit.cover,
        errorBuilder: (BuildContext context, o, s) {
          return Image.asset(
            "asset/images/noPhoto.png",
            fit: BoxFit.cover,
          );
        },
      ),
    );

Image.file

ローカルファイル形式で画像を表示する方法です。
image_pickerで取得したファイルはこの方法で表示できます。

// image picker
XFile? image = await ImagePicker().pickImage(source:ImageSource.gallery);

final pickedImage;
if(image == null){
  return;
}
pickedImage = File(image.path);

image_picker:
https://pub.dev/packages/image_picker

Image.memory

Uint8List形式で画像を表示する方法です。Base64コードの画像データはこの方法で表示できます。
変換方法については後述します。

変換について

  • URLからUint8Listへ変換する
Uint8List imageBytes =
          (await NetworkAssetBundle(Uri.parse(path)).load(path)).buffer.asUint8List();
  • アセットファイルをUinit8Listへ変換
    // アセットからデータをロードする
    final byteData = await rootBundle.load(assetPath);
    Uint8List imageBytes =
        byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes);
  • アセットファイルをImageへ変換
Future<ui.Image>? loadImageFromAssets(String path) async {
  ByteData data = await rootBundle.load(path);
  return decodeImageFromList(data.buffer.asUint8List());
}
  • fileからBase64へ変換
final file;
List<int> imageBytes = await file.readAsBytes();
// base64 code
String base64Image = base64Encode(imageBytes);
  • Base64からUint8List
Uint8List unit8 = base64Decode(base64);
8
8
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
8
8