exif-jsを使ってEXIF情報から画像の向きを取得する

exif-jsを使ってEXIF情報から画像の向きを取得する方法です。

exif-jsをインストールする。

npm install exif-js --save-dev

exif-jsを読み込む。

import EXIF from "exif-js";

画像ファイルを選択する。

<input type="file" id="target" accept="image/*">

画像ファイルが選択されたら、処理を実行する。

const target = document.getElementById('target');
target.addEventListener('change', (e) => {
    // 選択された画像ファイルの処理
});

選択された画像ファイルを読み込む。

// 選択された画像ファイルの処理
const file = e.target.files[0];
const reader = new FileReader();
reader.onloadend = function () {
    const image = new Image();
    image.src = reader.result;
    image.onload = function () {
        // 読み込んだ画像ファイルの処理
    });
};
reader.readAsDataURL(file);

画像ファイルのEXIF情報を取得する。

// 読み込んだ画像ファイルの処理
EXIF.getData(image, function () {
    const orientation = EXIF.getTag(this, 'Orientation');
    // 画像の向き
    console.log(`orientation = ${orientation}`);
    // すべての情報
    console.log(EXIF.getAllTags(this));
});

HTMLファイル

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EXIF Sample</title>
</head>
<body>
    <p>↓画像ファイルを選択します。</p>
    <input type="file" id="target" accept="image/*">
    <script src="bundle.js"></script>
</body>
</html>

JavaScript

import EXIF from "exif-js";
const target = document.getElementById('target');
target.addEventListener('change', (e) => {
    // 選択された画像ファイルの処理
    const file = e.target.files[0];
    const reader = new FileReader();
    reader.onloadend = function () {
        const image = new Image();
        image.src = reader.result;
        image.onload = function () {
            // 読み込んだ画像ファイルの処理
            EXIF.getData(image, function () {
                const orientation = EXIF.getTag(this, 'Orientation');
                // 画像の向き
                console.log(`orientation = ${orientation}`);
                // すべての情報
                console.log(EXIF.getAllTags(this));
            });
        };
    };
    reader.readAsDataURL(file);
});

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください