C# 如何获取照片中Exif信息里GPS信息与经纬度数
C# 如何获取照片中Exif信息里GPS信息与经纬度数
附加段相关代码
#region
//載入圖片
Image objImage = Image.FromFile("E:\\Pictures\\20080512131.jpg");
//取得所有的屬性(以PropertyId做排序)
var propertyItems = objImage.PropertyItems.OrderBy(x => x.Id);
//暫訂緯度為N(北緯)
char chrGPSLatitudeRef = 'N';
//暫訂經度為E(東經)
char chrGPSLongitudeRef = 'E';
foreach (PropertyItem objItem in propertyItems)
{
//只取Id範圍為0x0000到0x001e
if (objItem.Id >= 0x0000 && objItem.Id <= 0x001e)
{
objItem.Id = 0x0002;
switch (objItem.Id)
{
case 0x0000:
var query = from tmpb in objItem.Value select tmpb.ToString();
string sreVersion = string.Join(".", query.ToArray());
richTextBox1.Text = sreVersion;
break;
case 0x0001:
chrGPSLatitudeRef = BitConverter.ToChar(objItem.Value, 0);
break;
case 0x0002:
if (objItem.Value.Length == 24)
{
//degrees(將byte[0]~byte[3]轉成uint, 除以byte[4]~byte[7]轉成的uint)
double d = BitConverter.ToUInt32(objItem.Value, 0) * 1.0d / BitConverter.ToUInt32(objItem.Value, 4);
//minutes(將byte[8]~byte[11]轉成uint, 除以byte[12]~byte[15]轉成的uint)
double m = BitConverter.ToUInt32(objItem.Value, 8) * 1.0d / BitConverter.ToUInt32(objItem.Value, 12);
//seconds(將byte[16]~byte[19]轉成uint, 除以byte[20]~byte[23]轉成的uint)
double s = BitConverter.ToUInt32(objItem.Value, 16) * 1.0d / BitConverter.ToUInt32(objItem.Value, 20);
//計算緯度的數值, 如果是南緯, 要乘上(-1)
double dblGPSLatitude = (((s / 60 + m) / 60) + d) * (chrGPSLatitudeRef.Equals('N') ? 1 : -1);
string strLatitude = string.Format("{0:#} deg {1:#}' {2:#.00}\" {3}", d, m, s, chrGPSLatitudeRef);
}
break;
case 0x0003:
//透過BitConverter, 將Value轉成Char('E' / 'W')
//此值在後續的Longitude計算上會用到
chrGPSLongitudeRef = BitConverter.ToChar(objItem.Value, 0);
break;
case 0x0004:
if (objItem.Value.Length == 24)
{
//degrees(將byte[0]~byte[3]轉成uint, 除以byte[4]~byte[7]轉成的uint)
double d = BitConverter.ToUInt32(objItem.Value, 0) * 1.0d / BitConverter.ToUInt32(objItem.Value, 4);
//minutes(將byte[8]~byte[11]轉成uint, 除以byte[12]~byte[15]轉成的uint)
double m = BitConverter.ToUInt32(objItem.Value, 8) * 1.0d / BitConverter.ToUInt32(objItem.Value, 12);
//seconds(將byte[16]~byte[19]轉成uint, 除以byte[20]~byte[23]轉成的uint)
double s = BitConverter.ToUInt32(objItem.Value, 16) * 1.0d / BitConverter.ToUInt32(objItem.Value, 20);
//計算緯度的數值, 如果是西經, 要乘上(-1)
double dblGPSLongitude = (((s / 60 + m) / 60) + d) * (chrGPSLongitudeRef.Equals('E') ? 1 : -1);
Console.WriteLine("{0:#} deg {1:#}' {2:#.00}\" {3}", d, m, s, chrGPSLongitudeRef);
}
break;
case 0x0005:
string strAltitude = BitConverter.ToBoolean(objItem.Value, 0) ? "0" : "1";
break;
case 0x0006:
if (objItem.Value.Length == 8)
{
//將byte[0]~byte[3]轉成uint, 除以byte[4]~byte[7]轉成的uint
double dblAltitude = BitConverter.ToUInt32(objItem.Value, 0) * 1.0d / BitConverter.ToUInt32(objItem.Value, 4);
}
break;
}
}
}
#endregion