JPEG Exif UserComment (JPEGファイルのメタデータ) を読み込むコードと実行結果の紹介です。
PNGファイルではPNG Infoに作成者の情報が格納される場合がありますが、
JPEGファイルの場合は、PNG Infoと同じ仕組みは無いため、テキスト情報を Exif領域に書き込んでいる場合があります。
この記事では、JPEGファイルのExif UserCommentの値を取得するコードを紹介します。
今回はWindows Formアプリケーションで実装します。Windows Formアプリケーションのプロジェクトを作成し、
ImageSharpをインストールします。
NuGetを利用したインストールについては、以下の記事を参照してください。
下図のフォームを作成します。TextBoxを2つ、Buttonを2つ、OpenFileDialogを配置しています。
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Metadata.Profiles.Exif;
using System.Text;
using static System.Net.Mime.MediaTypeNames;
namespace ReadJpegExif
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK) {
textBox2.Text = openFileDialog1.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
SixLabors.ImageSharp.Image img = SixLabors.ImageSharp.Image.Load(textBox2.Text);
if (img.Metadata.DecodedImageFormat != JpegFormat.Instance) {
textBox1.Text += "JPEG 形式ではありません";
return;
}
ExifProfile exifProfile = img.Metadata.ExifProfile;
if (exifProfile != null) {
// ExifTag.UserComment を探す
IExifValue<EncodedString>? UserComment;
exifProfile.TryGetValue(ExifTag.UserComment, out UserComment);
if (UserComment != null) {
string OrgValue = UserComment.GetValue()?.ToString();
byte[] beBytes = Encoding.BigEndianUnicode.GetBytes(orgValue);
metaData = Encoding.Unicode.GetString(beBytes);
textBox1.Text += DecodedValue;
}
}
}
}
}
ファイルパスからイメージを読み込みます。
SixLabors.ImageSharp.Image img = SixLabors.ImageSharp.Image.Load(textBox2.Text);
MedtadataプロパティのDecodedImageFormatの値を判定してJPEGファイルかを判定します。
if (img.Metadata.DecodedImageFormat != JpegFormat.Instance) {
textBox1.Text += "JPEG 形式ではありません";
return;
}
JPEGファイルの場合は、Metadata.ExifProfile プロパティを取得してExifメタデータを取得します。
ExifProfile exifProfile = img.Metadata.ExifProfile;
取得したメタデータが存在する場合は、TryGetValue() メソッドを呼び出し、UserCommentの値を取得します。
if (exifProfile != null) {
// ExifTag.UserComment を探す
IExifValue<EncodedString>? UserComment;
exifProfile.TryGetValue(ExifTag.UserComment, out UserComment);
/*
略
*/
}
UserCommentの値は取得した状態では、UTF-16 Little Endian(UTF-16LE) でエンコードされたデータのため、
UTF-16 Big Endian(UTF-16BE)に変換します。
string OrgValue = UserComment.GetValue()?.ToString();
byte[] beBytes = Encoding.BigEndianUnicode.GetBytes(OrgValue);
string DecodedValue = Encoding.Unicode.GetString(beBytes);
変換された値をテキストボックスに出力します。
textBox1.Text += DecodedValue;
下図の画像を用意します。Stable Diffusionで生成されたグリッドのjpeg画像です。
プロジェクトを実行します。下図のウィンドウが表示されます。
[button2]をクリックします。ファイルを開くダイアログが表示されます。先に準備したJPEG画像を選択して開きます。
JPEG画像のファイルパスが上部のテキストボックスに表示されます。
[button1]をクリックします。JPEG画像内のExifのUserCommentの値が下部のテキストボックスに表示されます。
JPEGファイル内に埋め込まれたUserCommentの値を読み込むことができました。