0
0

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 1 year has passed since last update.

Flutter image_pickerで端末から取得した画像のサイズ(メガバイト)を出す

Posted at

はじめに

Fluterで端末から画像を取得してアップロードするときなど、あらかじめ画像のサイズを知りたい場面がありました。

例えば、サーバーの容量を圧迫しないように、サイズが大き過ぎる画像はアップロードさせないなどなどの処理を入れたい場合などである。

画像を扱うパッケージはもちろんimage_picker

また、コードはriverpodで状態管理をしてあります。

画像を端末から取得する

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

  static final pickImageFromGallery = Provider.autoDispose(
    (ref) => () async {
      final image = await ImagePicker().pickImage(
      // 画像を取得する
        source: ImageSource.gallery,
      );
      if (image != null) {
        // バイト配列(Uint8List)へ変換
        final imageBytes = await image.readAsBytes();
        // 画像のバイト数(サイズ)を取得
        final bytesLength = imageBytes.length;
        // 1メガバイトは1000キロバイト(KB)なので、バイト数を1000で割り、その結果をさらに1000で割る
        final mbAmount = bytesLength / 1000 / 1000;
        print("画像のサイズ: $mbAmount MB");
        return imageBytes;
      } else {
        return null;
      }
    },
  );

1MB = 1000000バイトなのでこのような式になってます。

1000000 / 1000 / 1000 = 1 MB

注意点

シュミレーターで試したところ、アプリで表示されるサイズと実際にログで確認できるサイズが若干異なることが多くありました:sweat:

Screenshot 2024-02-26 at 12.17.23.png
Screenshot 2024-02-26 at 12.17.39.png

シュミレーターにデフォルトで入ってる画像を確認すると、大枠あってる画像もありましたが少し違ってる画像もありました。

またHEIF形式の画像も違った数値で出力されていました。。。

Screenshot 2024-02-26 at 12.24.44.png

うーん、画像を扱うのはほんと難しいですね〜:joy_cat:

もっと他にいい方法や性格に画像サイズを計れる方法があれば教えてください!

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?