Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#
Article

EXIFextractor library to extract EXIF information

Rate me:
Please Sign up or sign in to vote.
4.91/5 (39 votes)
7 Sep 20054 min read 471.1K   19.3K   179   80
EXIFextractor library to extract EXIF information.

Image 1

Introduction

OK, here is the problem, you have an image and you either want to set some EXIF tag in it or read some EXIF tag embedded in it. Solution...? well part of it has already being implemented by MS in .NET but that is just the tag number and raw data associated with it. Clearly this does not help us in any way when a user just wants to read the image comments. First you must know the tag number, then using .NET you extract that tag and then convert it. Well on the first hand it doesn't sound that bad (which if you take my word is really not bad if you are concerned with just ASCII strings) but say you want to extract ISO speed which ironically is in rational number format or other data types that require conversions, then you will agree that not only it's bad it can be sometimes stupid. If you are a person like me you will scratch your head first and think why are they trying to trick us by embedding the data like that? They could have easily done that in other simpler formats, but guess what? It's already done and you are the lucky one who is going to do all the decoding. What you have read in the previous lines were part of my emotions, when I set out to make an EXIF control for this website.

I will continue to update this control on my website so in case you are looking at this article in 2006 (and provided humans don't start WW3) there are some good chances that you will find the latest version there.

Background

Basic match knowledge, along with basic C# knowledge and idea about the Bitmap class. Oh yes 1 Brain (but it's optional).

Using the code

EXIFextractor is a very lightweight class, which you can just pass in your Bitmap as a reference and this class will use it. The bitmap won't be modified unless you call the setTag function to change a specific tag. It will be your job to store/save the bitmap once you have added/modified a tag.

Here is a sample code that shows you how to dump all the tags on a console.

C#
System.Drawing.Bitmap bmp = 
             new System.Drawing.Bitmap("F:\\DSCI0006.JPG");

// create a new instance of Extractor 
// class. Here "\n" is the newline 
// that is used to seprate output of two tags. 
// You can replace it with "," if you want
Goheer.EXIF.EXIFextractor er = 
             new Goheer.EXIF.EXIFextractor(ref bmp,"\n");

// now dump all the tags on console
Console.Write(er); 

// to set a tag you have to specify the tag id
// code 0x13B is for artist name
// since this number has ascii string with 
// it pass the string you want to set
er.setTag(0x13B,"http://www.goheer.com");

// dispose the image here or do whatever you want.
//

If you want to get individual items such as artist name. Please keep in mind that this can return null for EXIF properties that are not present in the system, so it's a right thing to check for null values before doing any operation.

C#
Console.Write(er["Equip Make"]);

You can also use enumerator like foreach and get all the properties one by one. Here a point worth mentioning is that the data is returned in the form of System.Web.UI.Pair object.

C#
Goheer.EXIF.EXIFextractor er = 
              new Goheer.EXIF.EXIFextractor(ref bmp,"");
foreach(System.Web.UI.Pair s in er )
{
    // Remember the data is returned 
    // in a Key,Value Pair object
    Console.Write(s.First+"  " + s.Second +"\n");
}

Here is the list of properties that you can get using this method, all the values returned in this case will be converted to string values.

C#
/// <SUMMARY>
/// Get the individual property value by supplying property name
/// These are the valid property names :
/// 
/// "Exif IFD"
/// "Gps IFD"
/// "New Subfile Type"
/// "Subfile Type"
/// "Image Width"
/// "Image Height"
/// "Bits Per Sample"
/// "Compression"
/// "Photometric Interp"
/// "Thresh Holding"
/// "Cell Width"
/// "Cell Height"
/// "Fill Order"
/// "Document Name"
/// "Image Description"
/// "Equip Make"
/// "Equip Model"
/// "Strip Offsets"
/// "Orientation"
/// "Samples PerPixel"
/// "Rows Per Strip"
/// "Strip Bytes Count"
/// "Min Sample Value"
/// "Max Sample Value"
/// "X Resolution"
/// "Y Resolution"
/// "Planar Config"
/// "Page Name"
/// "X Position"
/// "Y Position"
/// "Free Offset"
/// "Free Byte Counts"
/// "Gray Response Unit"
/// "Gray Response Curve"
/// "T4 Option"
/// "T6 Option"
/// "Resolution Unit"
/// "Page Number"
/// "Transfer Funcition"
/// "Software Used"
/// "Date Time"
/// "Artist"
/// "Host Computer"
/// "Predictor"
/// "White Point"
/// "Primary Chromaticities"
/// "ColorMap"
/// "Halftone Hints"
/// "Tile Width"
/// "Tile Length"
/// "Tile Offset"
/// "Tile ByteCounts"
/// "InkSet"
/// "Ink Names"
/// "Number Of Inks"
/// "Dot Range"
/// "Target Printer"
/// "Extra Samples"
/// "Sample Format"
/// "S Min Sample Value"
/// "S Max Sample Value"
/// "Transfer Range"
/// "JPEG Proc"
/// "JPEG InterFormat"
/// "JPEG InterLength"
/// "JPEG RestartInterval"
/// "JPEG LosslessPredictors"
/// "JPEG PointTransforms"
/// "JPEG QTables"
/// "JPEG DCTables"
/// "JPEG ACTables"
/// "YCbCr Coefficients"
/// "YCbCr Subsampling"
/// "YCbCr Positioning"
/// "REF Black White"
/// "ICC Profile"
/// "Gamma"
/// "ICC Profile Descriptor"
/// "SRGB RenderingIntent"
/// "Image Title"
/// "Copyright"
/// "Resolution X Unit"
/// "Resolution Y Unit"
/// "Resolution X LengthUnit"
/// "Resolution Y LengthUnit"
/// "Print Flags"
/// "Print Flags Version"
/// "Print Flags Crop"
/// "Print Flags Bleed Width"
/// "Print Flags Bleed Width Scale"
/// "Halftone LPI"
/// "Halftone LPIUnit"
/// "Halftone Degree"
/// "Halftone Shape"
/// "Halftone Misc"
/// "Halftone Screen"
/// "JPEG Quality"
/// "Grid Size"
/// "Thumbnail Format"
/// "Thumbnail Width"
/// "Thumbnail Height"
/// "Thumbnail ColorDepth"
/// "Thumbnail Planes"
/// "Thumbnail RawBytes"
/// "Thumbnail Size"
/// "Thumbnail CompressedSize"
/// "Color Transfer Function"
/// "Thumbnail Data"
/// "Thumbnail ImageWidth"
/// "Thumbnail ImageHeight"
/// "Thumbnail BitsPerSample"
/// "Thumbnail Compression"
/// "Thumbnail PhotometricInterp"
/// "Thumbnail ImageDescription"
/// "Thumbnail EquipMake"
/// "Thumbnail EquipModel"
/// "Thumbnail StripOffsets"
/// "Thumbnail Orientation"
/// "Thumbnail SamplesPerPixel"
/// "Thumbnail RowsPerStrip"
/// "Thumbnail StripBytesCount"
/// "Thumbnail ResolutionX"
/// "Thumbnail ResolutionY"
/// "Thumbnail PlanarConfig"
/// "Thumbnail ResolutionUnit"
/// "Thumbnail TransferFunction"
/// "Thumbnail SoftwareUsed"
/// "Thumbnail DateTime"
/// "Thumbnail Artist"
/// "Thumbnail WhitePoint"
/// "Thumbnail PrimaryChromaticities"
/// "Thumbnail YCbCrCoefficients"
/// "Thumbnail YCbCrSubsampling"
/// "Thumbnail YCbCrPositioning"
/// "Thumbnail RefBlackWhite"
/// "Thumbnail CopyRight"
/// "Luminance Table"
/// "Chrominance Table"
/// "Frame Delay"
/// "Loop Count"
/// "Pixel Unit"
/// "Pixel PerUnit X"
/// "Pixel PerUnit Y"
/// "Palette Histogram"
/// "Exposure Time"
/// "F-Number"
/// "Exposure Prog"
/// "Spectral Sense"
/// "ISO Speed"
/// "OECF"
/// "Ver"
/// "DTOrig"
/// "DTDigitized"
/// "CompConfig"
/// "CompBPP"
/// "Shutter Speed"
/// "Aperture"
/// "Brightness"
/// "Exposure Bias"
/// "MaxAperture"
/// "SubjectDist"
/// "Metering Mode"
/// "LightSource"
/// "Flash"
/// "FocalLength"
/// "Maker Note"
/// "User Comment"
/// "DTSubsec"
/// "DTOrigSS"
/// "DTDigSS"
/// "FPXVer"
/// "ColorSpace"
/// "PixXDim"
/// "PixYDim"
/// "RelatedWav"
/// "Interop"
/// "FlashEnergy"
/// "SpatialFR"
/// "FocalXRes"
/// "FocalYRes"
/// "FocalResUnit"
/// "Subject Loc"
/// "Exposure Index"
/// "Sensing Method"
/// "FileSource"
/// "SceneType"
</SUMMARY>

Here is how the class works. We take the PropertyItem array provided by .NET and then convert it to human readable form according to the EXIF standards. I am chopping off the extra details here you can see them in the code provided. Basically there are 6 types of data types that are normally embedded in an image. We take each one and treat them differently. Sometimes in a specific data type we have to do extra conversion for a specific tag (i.e. iso), we have to perform specific calculations on the data after which we will get the human readable form. There are many such conversions done in this loop which again I have removed on purpose.

C#
System.Drawing.Imaging.PropertyItem [] y = 
                                 bmp.PropertyItems;
//
foreach(System.Drawing.Imaging.PropertyItem p in y)
{
    //1 = BYTE An 8-bit unsigned integer.,
    if( p.Type == 0x1 )
    {
        //byte
    }
        //2 = ASCII An 8-bit byte 
        //containing one 7-bit ASCII 
        //code. The final byte 
        //is terminated with NULL.,
    else if( p.Type == 0x2 )
    {
        // string                    

    }
        //3 = SHORT A 16-bit (2 -byte) 
        //unsigned integer,
    else if( p.Type == 0x3 )
    {
        // short int
    }
        //4 = LONG A 32-bit (4 -byte) 
        //unsigned integer,
    else if( p.Type == 0x4 )
    {
        // unsigned int

    }
        //5 = RATIONAL Two LONGs. The 
        //first LONG is the numerator 
        //and the second LONG expresses 
        //the denominator.,
    else if( p.Type == 0x5 )
    {
        // rational
        
    }
        //7 = UNDEFINED An 8-bit 
        //byte that can take 
        //any value depending on 
        //the field definition,
    else if( p.Type == 0x7 )
    {
        // depends upon the tag what form the 
        // data can take. no universal rule
    }
}

As you can see the basic concept is straight but the things you have to do for data conversion kills you.

Last thing to remember is that this code is provided as it is, if it fortunately destroys all of your precious image collection then no one is to be blamed except you ;).

Points of interest

If you want to see the scalability of this control then you should definitely visit this site. On this site when a user uploads a picture all the data is automatically extracted from the image, along with that the image is checked for duplicates if someone else has uploaded that same image or not. Then in the next stage thumbnail images are created, so basically you can say that this site works on its own.

History

I wrote my first article on how to display screensaver on both screens of a dual monitor. If any of you guys have free time then do check it out and give me suggestions/comments about that too. It's called GxTS.

Image 2

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralSystem.ArgumentException was unhandled when try setTag Pin
pa_duch3-Jan-09 13:14
pa_duch3-Jan-09 13:14 
GeneralShutter Speed Issue Pin
Hardy Wang29-Dec-08 3:08
Hardy Wang29-Dec-08 3:08 
QuestionAnybody knows how to convert this class to Compact Framework? Pin
LEM329-Apr-08 13:06
LEM329-Apr-08 13:06 
QuestionHow to get valid GPS coordinates [modified] Pin
blackmanticore21-Apr-08 4:54
blackmanticore21-Apr-08 4:54 
AnswerRe: How to get valid GPS coordinates Pin
LEM329-Apr-08 13:04
LEM329-Apr-08 13:04 
GeneralRe: How to get valid GPS coordinates Pin
rrrrrrrrrrrd2-May-08 0:10
rrrrrrrrrrrd2-May-08 0:10 
GeneralRe: How to get valid GPS coordinates Pin
rrrrrrrrrrrd13-May-08 23:12
rrrrrrrrrrrd13-May-08 23:12 
AnswerRe: How to get valid GPS coordinates Pin
Bangassou8-Jul-08 0:29
Bangassou8-Jul-08 0:29 
For all Germans who need a conversion from WGS84 to Gauss Krueger I post my solution which works great:

public Int16 Transform_WGS84_2_GK ( double rLatDec, double rLonDec, double rH, ref double rLongitude, ref double rLatitude)
{
double rWGS_a = 6378137.000;
double rWGS_b = 6356752.314;

double Bessel_a = 6377397.155;
double Bessel_b = 6356078.962;

double TPdx = 598.1;
double TPdy = 73.7;
double TPdz = 418.2;
double TPex = -0.202;
double TPey = -0.045;
double TPez = 2.455;
double TPm = 6.7;

double rWGS_E2, rWGS_N;
double rVecX, rVecY, rVecZ;
double F2, F3, F4, F5, F6, F7, F8;
double rotVec1,rotVec2, rotVec3;
double trans1, trans2, trans3;
double s5;
double T5;
double B5;
double L5;
double N5;
double h5,B,L,h;
double Bessel_e2;
double n6, alpha, beta, gamma, delta, epsilon;
int L0;
double l6, B6, N6_, nano, t6;
double Bogenlaenge;
double h1,h2,r1,r2;

rWGS_E2 = ( Sqr(rWGS_a) - Sqr(rWGS_b))/ (Sqr(rWGS_a));

rWGS_N = (rWGS_a)/(Math.Sqrt( 1 - rWGS_E2*Sqr(Math.Sin( rLatDec/180*Math.PI))));

rVecX = (rWGS_N + rH) * Math.Cos(rLatDec / 180 * Math.PI) * Math.Cos(rLonDec / 180 * Math.PI);
rVecY = (rWGS_N + rH) * Math.Cos(rLatDec / 180 * Math.PI) * Math.Sin(rLonDec / 180 * Math.PI);
rVecZ = ( rWGS_N * Sqr(rWGS_b)/Sqr( rWGS_a) + rH) * Math.Sin( rLatDec / 180 * Math.PI);


F5 = -TPex * Math.PI / 180 / 3600;
F6 = -TPey * Math.PI / 180 / 3600;
F7 = -TPez * Math.PI / 180 / 3600;
F8 = 1 - TPm/1000000;

F2 = -( TPdx + F7*TPdy - F6*TPdz);
F3 = -(-F7*TPdx + TPdy + F5*TPdz);
F4 = -( F6*TPdx - F5*TPdy + TPdz);


rotVec1 = ( rVecX + F7*rVecY - F6*rVecZ) * F8;
rotVec2 = (-F7*rVecX + rVecY + F5*rVecZ) * F8;
rotVec3 = ( F6*rVecX - F5*rVecY + rVecZ) * F8;

trans1 = rotVec1 + F2;
trans2 = rotVec2 + F3;
trans3 = rotVec3 + F4;

s5 = Math.Sqrt(Sqr(trans1) + Sqr(trans2));
Bessel_e2 = (Sqr(Bessel_a)-Sqr(Bessel_b))/Sqr(Bessel_a);
T5 = Math.Atan( trans3 * Bessel_a / (s5 * Bessel_b));
B5 = Math.Atan((trans3 + Bessel_e2 * Sqr(Bessel_a) / Bessel_b * Math.Pow(Math.Sin(T5), 3)) / (s5 - Bessel_e2 * Bessel_a * Math.Pow(Math.Cos(T5), 3)));
L5 = Math.Atan( trans2 / trans1);
N5 = Bessel_a/Math.Sqrt(1-Bessel_e2 * Sqr(Math.Sin(B5)));
h5 = (s5 / Math.Cos(B5)) - N5;

B = B5 * 180 / Math.PI;
L = L5 * 180 / Math.PI;
h = h5;

n6 = (Bessel_a - Bessel_b)/(Bessel_a + Bessel_b);
alpha = ((Bessel_a + Bessel_b)/2) * ( 1 + 0.25*Sqr(n6) + 1/64*Math.Pow(n6,4));
beta = -1.5*n6 + 9/16*Math.Pow(n6,3) - 3/32*Math.Pow(n6,5);
gamma = 15/16 * Sqr(n6) - 15/32*Math.Pow(n6,4);
delta = -35/48*Math.Pow(n6,3) + 105/256*Math.Pow(n6,5);
epsilon = 315/512*Math.Pow(n6,4);

if( Math.Abs(L-6) < 1.5)
L0 = 6;
else if (Math.Abs(L - 9) < 1.5)
L0 = 9;
else if (Math.Abs(L - 12) < 1.5)
L0 = 12;
else if (Math.Abs(L - 15) < 1.5)
L0 = 15;
else
{
MessageBox.Show( "Länge nicht unterstützt! Koordinatentransformation nur für Deutschland!");
L0 = -1;
}
if (L0 > 0)
{
l6 = (L - L0) * Math.PI / 180;
B6 = B * Math.PI / 180;
N6_ = Bessel_a / Math.Sqrt(1 - Bessel_e2 * Sqr(Math.Sin(B6)));
nano = Math.Sqrt(Sqr(Bessel_a) / Sqr(Bessel_b) * Bessel_e2 * Sqr(Math.Cos(B6)));
t6 = Math.Tan(B6);

Bogenlaenge = alpha * (B6 + beta * Math.Sin(2 * B6) + gamma * Math.Sin(4 * B6) + delta * Math.Sin(6 * B6) + epsilon * Math.Sin(8 * B6));
h1 = t6 / 2 * N6_ * Sqr(Math.Cos(B6)) * Sqr(l6);
h2 = t6 / 24 * N6_ * Math.Pow(Math.Cos(B6), 4) * (5 - Sqr(t6) + 9 * Sqr(nano) + 4 * Math.Pow(nano, 4)) * Math.Pow(l6, 4);
// h3 := t6/720*N6_*Power(Cos(B6),6)*(61 - 58*Sqr(t6) + 270*Sqr(nano) - 330*Sqr(t6)*Sqr(nano))*Power(l6,6);
// h4 := t6/40320*N6_*Power(Cos(B6),8)*(1385-3111*Sqr(t6) + 543*Power(t6,4) - Power(t6,6))*Power(l6,8);

rLatitude = Bogenlaenge + h1 + h2;

r1 = N6_ * Math.Cos(B6) * l6;
r2 = N6_ / 6 * Math.Pow(Math.Cos(B6), 3) * (1 - Sqr(t6) + Sqr(nano)) * Math.Pow(l6, 3);

rLongitude = r1 + r2 + 500000 + L0 / 3 * 1000000;
}

return 0;
}
private double Sqr(double r)
{
return ( Math.Pow( r, 2.0));
}
AnswerRe: How to get valid GPS coordinates Pin
Mario Campo16-Jul-08 0:40
Mario Campo16-Jul-08 0:40 
AnswerRe: How to get valid GPS coordinates Pin
cookie_biscuit27-Mar-09 18:31
cookie_biscuit27-Mar-09 18:31 
AnswerRe: How to get valid GPS coordinates [modified] Pin
Jordan Nash17-Jun-18 15:39
Jordan Nash17-Jun-18 15:39 
Generaljpg file gets locked after using this library Pin
rav6-Apr-08 7:22
rav6-Apr-08 7:22 
GeneralRe: jpg file gets locked after using this library Pin
Greg Cadmes10-May-08 5:28
Greg Cadmes10-May-08 5:28 
QuestionRAW Image data Pin
mvanschie3-Jan-08 21:54
mvanschie3-Jan-08 21:54 
AnswerRe: RAW Image data Pin
glenneroo27-Nov-10 15:25
glenneroo27-Nov-10 15:25 
Generalabout GPS photo Pin
SILENCE22616-Sep-07 6:57
SILENCE22616-Sep-07 6:57 
Generalclosing FileStream and some updated buildDB cases Pin
davidhart12-Jul-07 8:54
davidhart12-Jul-07 8:54 
GeneralRe: closing FileStream and some updated buildDB cases Pin
3soft3-Sep-10 10:32
3soft3-Sep-10 10:32 
QuestionNullReferenceException was unhandled Pin
puyopuy28-Jun-07 19:16
puyopuy28-Jun-07 19:16 
Questionsystem.web.ui ? Pin
coldkatz2-Jun-07 5:03
coldkatz2-Jun-07 5:03 
AnswerRe: system.web.ui ? Pin
Asim Goheer2-Jun-07 7:14
Asim Goheer2-Jun-07 7:14 
GeneralRe: system.web.ui ? Pin
David Catriel3-Jun-07 13:06
David Catriel3-Jun-07 13:06 
GeneralRe: system.web.ui ? Pin
David Catriel3-Jun-07 13:13
David Catriel3-Jun-07 13:13 
QuestionGPS Information Pin
MarkRedman30-May-07 21:38
MarkRedman30-May-07 21:38 
AnswerRe: GPS Information Pin
Asim Goheer2-Jun-07 7:16
Asim Goheer2-Jun-07 7:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.