LoginSignup
1
1

More than 1 year has passed since last update.

[Cloud Functions] FirebaseStorage に保存された画像の幅と高さを取得する

Last updated at Posted at 2022-05-15

Flutter / Firebase のアプリ開発で実装したことを記事にしました。
誰かのお役に立てれば幸いです。

アプリから、FirebaseStorage に画像を保存したときに、
その画像の width と height を取得する必要があったので、CloudFunctions 内で
画像サイズを取得する関数を作成しました。

パッケージの導入

画像サイズを取得するパッケージは、

こちらを使いました。コードが、とてもシンプルです。

画像パスから width , height を取得

まずは、Storage に保存された画像のパスと一時的に保存するディレクトリのパスを
用意する必要があります。
一時保存のディレクトリに画像をダウンロードしてから、サイズを取得する流れです。

import * as functions from "firebase-functions";
import * as fs from "fs";
import * as path from "path";
import * as os from "os";
import mkdirp from "mkdirp";
import * as admin from "firebase-admin";

const sizeOf = require('image-size')

export const testFunction = functions
  .region("asia-northeast1")
  .storage.object()
  .onFinalize(async (object) => {
    const fileName = object.name; // ファイル名
    if (fileName === undefined) return;

    // 一時的に保存するディレクトリのパスを作成
    const tmpLocalFilePath = path.join(os.tmpdir(), fileName);
    const tmpLocalDir = path.dirname(tmpLocalFilePath);

    // Storage内の画像を一時保存のディレクトリにダウンロード
    const storage = admin.storage();
    const bucket = storage.bucket(object.bucket);
    const storageFile = bucket.file(fileName);

    await mkdirp(tempLocalDir); // 一時保存のディレクトリを作成
    await storageFile.download({ destination: tmpLocalFilePath });

    const { width, height } = sizeOf(tmpLocalFilePath);  // 画像のサイズを取得
    
    fs.unlinkSync(tmpLocalFilePath);  // 一時保存のディレクトリの削除
    return Promise.resolve();
  });

参考にしたサイト

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