user1472131
user1472131

Reputation: 421

Reading exif data with .net framework (System.Drawing.Imaging)

I am using the .net framework to read the exif metadata from a jpg file. The problem is how to convert the PropertyItem.Value (that is byte array) in a readable form such as a string.

For example with this code I read the GPSAltitude value of a picture:

        var pic = System.Drawing.Image.FromFile(@"c:\mypic.jpg");
        var GPSAltitude = pic.GetPropertyItem(6);

and the GPSAltitude.Value is a byte array like this: {75,2,0,0,1,0,0,0}.

I know that the altitude is 587 m.s.l... but how do I go from that byte array to 587 ?

I tried to read it with ASCIIencoding and some other encodings but I get something like "K\0\0\0\0\0".

Any idea ? Thanks

Upvotes: 1

Views: 3067

Answers (3)

Chris Haas
Chris Haas

Reputation: 55427

Besides the answers already given, you might want to check out the actual Exif spec.

GPSAltitude (page 47)

Indicates the altitude based on the reference in GPSAltitudeRef. Altitude is expressed as one RATIONAL value. The reference unit is meters.

GPSAltitudeRef (page 47)

Indicates the altitude used as the reference altitude. If the reference is sea level and the altitude is above sea level, 0 is given. If the altitude is below sea level, a value of 1 is given and the altitude is indicated as an absolute value in the GPSAltitude tag. The reference unit is meters. Note that this tag is BYTE type, unlike other reference tags.

RATIONAL (Page 14)

Two LONGs. The first LONG is the numerator and the second LONG expresses the denominator.

LONG (Page 14)

A 32-bit (4-byte) unsigned integer.

So, {75, 2, 0, 0, 1, 0, 0, 0} is {75, 2, 0, 0} / {1, 0, 0, 0}. When you read the bytes as bits as little endian you get 0000 0010 0100 1011 / 0000 0000 0000 0001 which calculates to 587. The other answers explain how to get the answer but hopefully this explains why it is that way.

Upvotes: 6

goric
goric

Reputation: 11875

Simply convert your byte[] to an int to see the 587 value you expect:

var pic = System.Drawing.Image.FromFile(@"c:\mypic.jpg");         
var GPSAltitude = pic.GetPropertyItem(6); 
var altitude = System.BitConverter.ToInt32(GPSAltitude,0);

Upvotes: 2

adt
adt

Reputation: 4360

Probably BitConverter will work.

public static void Main()
   {

      byte[] bytes = {75, 2, 0, 0, 1, 0, 0, 0};
      int result = BitConverter.ToInt32(bytes, 0);
      Console.WriteLine("Returned value: {0}", result);
      Console.ReadLine();
   }

Result is : 587

Upvotes: 2

Related Questions