C#读取数码照片Exif信息

数码设备在生成JPG照片的时候会保存Exif信息,这些信息包含照片拍摄的一些参数,包括从拍摄时间到拍摄设备、曝光参数等等很多信息。
C#中从文件打开图像文件的时候,可以取得PropertyItem数组,里面记录了Exif参数的Dictionary。

[code=’c#’]
Image img = Image.FromFile(filePath);
PropertyItem[] pt = img.PropertyItems;
[/code]

PropertyItem类包含四个属性:

Type的定义:

  • 1 指定 Value 为字节数组。
  • 2 指定 Value 为空终止 ASCII 字符串。如果将类型数据成员设置为 ASCII 类型,则应该将 Len 属性设置为包括空终止的字符串长度。例如,字符串“Hello”的长度为 6。
  • 3 指定 Value 为无符号的短(16 位)整型数组。
  • 4 指定 Value 为无符号的长(32 位)整型数组。
  • 5 指定 Value 数据成员为无符号的长整型对数组。每一对都表示一个分数;第一个整数是分子,第二个整数是分母。
  • 6 指定 Value 为可以包含任何数据类型的值的字节数组。
  • 7 指定 Value 为有符号的长(32 位)整型数组。
  • 10 指定 Value 为有符号的长整型对数组。每一对都表示一个分数;第一个整数是分子,第二个整数是分母。

不同的类型都需要不同的解析方式。后面我给出两个附件,包含这些解析的函数的一个类。
其中cs文件是我整理过的,直接可以用,zip文件是参考代码。

[code=’c#’]
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace JPGCompact
{
class TestExif
{
public void DoTest(string filePath)
{
Image img = Image.FromFile(filePath);
PropertyItem[] pt = img.PropertyItems;

for (int i = 0; i < pt.Length; i++) { PropertyItem p = pt[i]; // 设备制造商 if (pt[i].Id == 0x010F) { //tbExifCamera.Text = ascii.GetString(pt[i].Value); } // 设备型号 if (pt[i].Id == 0x0110) { tbExifCamera.Text = ExifMeta.FormatValue(p); } // 拍照时间 if (pt[i].Id == 0x0132) { tbExifTime.Text = ExifMeta.FormatValue(p); } // 光圈 if (pt[i].Id == 0x9202) { tbExifAperture.Text = GetAperture(ExifMeta.FormatValue(p)); } // ISO if (pt[i].Id == 0x8827) { tbExifISO.Text = ExifMeta.FormatValue(p); } // 模式 if (pt[i].Id == 0x8822) { tbExifMode.Text = GetProgram(ExifMeta.FormatValue(p)); } } } } } [/code]

1 comment

  1. 谢谢!这才是好文章!支持下先!

发表评论