Web Toys

Discussion of all kinds of web technologies

About the author

Bret Patterson.
E-mail me Send mail

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Working with Image Metadata in .NET 3.0 Part I

Working with image metadata has always been pretty painful. There are several standards out there, with alot of overlap and data conversion to/from the meta data to consumable values is usually required. There have been numerous blogs and code samples for working with metadata in .NET 2.0, so I'm only going to focus on using the latest .NET 3.0.

In .NET 3.0 accessing basic image metadata is very simple.

First get the System.Windows.Media.Imaging.BitmapSource:

   1: public static BitmapSource GetBitmapSource(string filename)
   2: {
   3:     BitmapSource rv = null;
   4:     BitmapDecoder decoder;
   5:     if (File.Exists(filename))
   6:     {
   7:         using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
   8:         {
   9:             decoder = BitmapDecoder.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
  10:  
  11:             if (decoder != null)
  12:             {
  13:                 rv = decoder.Frames[0];
  14:             }
  15:  
  16:             fs.Close();
  17:         }
  18:     }
  19:  
  20: }

Next you can pull out all of the metadata into a Dictionary<string,string> using something simple like:

   1: public const string METADATA_TITLE = "Title";
   2: public const string METADATA_SUBJECT = "Subject";
   3: public const string METADATA_RATING = "Rating";
   4: public const string METADATA_LOCATION = "Location";
   5: public const string METADATA_KEYWORDS = "Keywords";
   6: public const string METADATA_FORMAT = "Format";
   7: public const string METADATA_DATETAKEN = "DateTaken";
   8: public const string METADATA_COPYRIGHT = "Copyright";
   9: public const string METADATA_COMMENT = "Comment";
  10: public const string METADATA_CAMERAMODEL = "CameraModel";
  11: public const string METADATA_CAMERAMANUFACTURER = "CameraManufacturer";
  12: public const string METADATA_AUTHOR = "Author";
  13: public const string METADATA_APPLICATIONNAME = "ApplicationName";
  14: public static void GetImageMetadata(Dictionary<string, string> result, BitmapSource bs)
  15: {
  16:  
  17:     if (bs != null)
  18:     {
  19:  
  20:         BitmapMetadata meta = bs.Metadata as BitmapMetadata;
  21:         if (meta.Title != null)
  22:         {
  23:             result.Add(METADATA_TITLE, meta.Title);
  24:         }
  25:         if (meta.Subject != null)
  26:         {
  27:             result.Add(METADATA_SUBJECT, meta.Subject);
  28:         }
  29:  
  30:         result.Add(METADATA_RATING, meta.Rating.ToString());
  31:         if (meta.Location != null)
  32:         {
  33:             result.Add(METADATA_LOCATION, meta.Location);
  34:         }
  35:         if (meta.Format != null)
  36:         {
  37:             result.Add(METADATA_FORMAT, meta.Format);
  38:         }
  39:         if (meta.DateTaken != null)
  40:         {
  41:             result.Add(METADATA_DATETAKEN, meta.DateTaken);
  42:         }
  43:         if (meta.Copyright != null)
  44:         {
  45:             result.Add(METADATA_COPYRIGHT, meta.Copyright);
  46:         }
  47:         if (meta.Comment != null)
  48:         {
  49:             result.Add(METADATA_COMMENT, meta.Comment);
  50:         }
  51:         if (meta.CameraModel != null)
  52:         {
  53:             result.Add(METADATA_CAMERAMODEL, meta.CameraModel);
  54:         }
  55:         if (meta.CameraManufacturer != null)
  56:         {
  57:             result.Add(METADATA_CAMERAMANUFACTURER, meta.CameraManufacturer);
  58:         }
  59:         StringBuilder keywords = new StringBuilder();
  60:         if (meta.Keywords != null)
  61:         {
  62:             foreach (string s in meta.Keywords)
  63:             {
  64:                 keywords.Append(s).Append(" ");
  65:             }
  66:             result.Add(METADATA_KEYWORDS, keywords.ToString().Trim());
  67:         }
  68:         if (meta.ApplicationName != null)
  69:         {
  70:             result.Add(METADATA_APPLICATIONNAME, meta.ApplicationName);
  71:         }
  72:         if (meta.Author != null)
  73:         {
  74:             StringBuilder authors = new StringBuilder();
  75:             foreach (string s in meta.Author)
  76:             {
  77:                 authors.Append(s).Append(",");
  78:             }
  79:             result.Add(METADATA_AUTHOR, authors.ToString().TrimEnd(new char[] { ',' }));
  80:         }
  81:  
  82:     }
  83: }

As you can see in the code .NET 3.0 provides some really useful convenience methods for accessing image metadata. You will also notice that the Keywords and Author properties are collections and can have multiple values. More on that later.

 

The above is fine if those are the only metadata fields you wish to access. If you want to access all of the metadata fields you need to use the new Query interface:

   1: BitmapMetadata meta = bs.Metadata;
   2: // to obtain the camera manufacturer
   3: // check if the data is present, otherwise you will get an exception in GetQuery
   4: if (bs.ContainsQuery("/xmp/tiff:make")) {
   5:     string CameraManufacturer = (string)bs.GetQuery("/xmp/tiff:make");
   6: }
   7: // or you can get the exif Camera Manufacturer
   8: if (bs.ContainsQuery("/app1/ifd/{ushort=271}")) {
   9:     string CameraManufacturer = (string)bs.GetQuery("/app1/ifd/{ushort=271}");
  10: }



Pretty nice. However those query syntaxes really leave alot to be desired. You can also use the following syntax to perform BOTH of the above in a priority order, with the first one called and if not data exists then it calls the second one:

   1: if (meta.ContainsQuery("System.Photo.CameraManufacturer")) {
   2:     string CameraManufacturer = (string)meta.GetQuery("System.Photo.CameraManufacturer");
   3: }


You can find all of the "System" query documentation at the following URL: http://msdn2.microsoft.com/en-us/library/bb643802.aspx
*NOTE: I recently opened a defect against microsoft for these fields, it appears this works for everything except those of type RATIONAL.

The documentation is for C/C++ code, however you can translate it into equivalent c# pretty easily.

One little quirk is that the code doesn't necessarily return very easy to work with data types. A good example of this is the System.Photo.DateTaken query returns a FILETIME object. You can convert this to a datetime object using:

 

   1: System.Runtime.InteropServices.ComTypes.FILETIME ft = (System.Runtime.InteropServices.ComTypes.FILETIME)_Value; 
   2:  
   3: DateTime time; 
   4:  
   5: long ticks = 0; 
   6:  
   7:  
   8:  
   9: ticks = ((long)ft.dwHighDateTime) << 32; 
  10:  
  11: += ft.dwLowDateTime; 
  12:  
  13: time = DateTime.FromFileTimeUtc(ticks); 

.NET 3.0 also allows you to modify these values using SetQuery, this will be the topic of Part II.


Posted by bpatters on Thursday, December 06, 2007 8:45 AM
Permalink | Comments (69) | Post RSSRSS comment feed

Comments

Robert Taubert United States

Monday, September 22, 2008 4:44 PM

Robert Taubert

I had found several articles that were supposed to show me how to access the Photo metadata.  Yours is the only one I could get to work.

I have to admit that I am only an amateur programer and thanks to a good C# to VB.net converter I got the first part working.  As soon as I get more time I want to play with the GetQuery code.

I will be looking forward to seeing Part II.

Thanks for sharing the code,

Robert Taubert United States

Wednesday, December 03, 2008 7:14 AM

Robert Taubert

Have you written the follow-up to "Working with Image Metadata in .NET 3.0 Part I"???

I certainly hope you still intend to write Part II.

Thank you,

Robert Taubert United States

Thursday, April 23, 2009 12:13 PM

Robert Taubert

Well, at least I know you are not dead.  You published an article a few days ago.

Would it be too much to ask for you to comment on whether you are going to write Part II to your article on Image Metadata?

Daniel Müller Germany

Wednesday, February 10, 2010 9:33 AM

Daniel Müller

I hope you keep up the good work, and are planning to write an article about how to extract specific fields from the camera maker from the exif tags. So far, I have been unable to figure out the correct queries for that. /hope

Criminal Public Records Search Bulgaria

Thursday, March 11, 2010 7:06 AM

Criminal Public Records Search

I really like your articles, but I cannot find your Rss feed

general<sp>electric<sp>cooktop United States

Friday, March 12, 2010 3:27 PM

general<sp>electric<sp>cooktop

Hvala<sp>vam<sp>za<sp>dobar<sp>post<sp>puno<sp>hvala

Jezreel Republic of the Philippines

Thursday, March 18, 2010 9:43 AM

Jezreel

Hey Robert can i have your c# to vb.net converter? i need this meta data too.. and if it is okay can i see you codes on how i can add keywords to image files?  

thanks for the author of this article :D

Jezreel Republic of the Philippines

Thursday, March 18, 2010 10:12 AM

Jezreel

im assuming that you can also do an article about writing meta data of image files :D

Bulgarian Property United States

Saturday, March 20, 2010 5:28 AM

Bulgarian Property

I like the blog, but could not find how to subscribe to receive the updates by email.

Night Stand lamp United States

Thursday, March 25, 2010 10:17 PM

Night Stand lamp

Where did you get this theme. Is this Wordpress?

Gerald Hellickson United States

Sunday, March 28, 2010 4:49 PM

Gerald Hellickson

I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites website list and will be checking back soon. Please check out my site as well and let me know what you think.

link building website United States

Monday, April 05, 2010 1:15 AM

link building website

Just my two cents, but your blog posts will look much more colorful if you can put in some pictures.

carpfishing United States

Monday, April 05, 2010 1:17 AM

carpfishing

Carp coarse fishing has to be understood by knowing what it is not.

Memorials United States

Wednesday, April 07, 2010 6:59 AM

Memorials

Hello nice blog im from london i found this on aol I seen it on the top ten searches i found this blog very interesting good luck with it i will return to this blog soon

Heavy Duty Shredder United States

Wednesday, April 21, 2010 12:07 AM

Heavy Duty Shredder

You have done an impressive post here. I presume by all the remarks that I am not alone benefiting from your posts. Thanks.

Patricia Fitch United States

Friday, April 23, 2010 2:53 PM

Patricia Fitch

Really good summary, this is very similar to a site that I have. Please check it out sometime and feel free to leave me a comenet on it and tell me what you think. Im always looking for feedback.

bum marketing United States

Monday, April 26, 2010 4:56 AM

bum marketing

i know i'm a little off topic, but i just wanted to say i like the layout of your blog. i'm new to the blogegine platform, so any tips on getting my blog looking good would be appreciated.

bum marketing United States

Monday, April 26, 2010 4:56 AM

bum marketing

i know i'm a little off topic, but i just wanted to say i like the layout of your blog. i'm new to the blogegine platform, so any suggestions on getting my blog looking good would be appreciated.

Millie Rieck United States

Tuesday, April 27, 2010 6:23 PM

Millie Rieck

Voucher-world - It´s time to shop for free! Receive free giftcards for doing easy and free surveys!

bum marketing United States

Tuesday, April 27, 2010 10:13 PM

bum marketing

i am subscribing. thanks

bum marketing United States

Tuesday, April 27, 2010 10:13 PM

bum marketing

i know this is not exactly on topic, but i run a blog using the blogengine platform as well and i'm having issues with my comments displaying. is there a setting i am missing? maybe you could help me out? thanx.

Berichtsportal Greece

Saturday, May 01, 2010 3:11 AM

Berichtsportal

Hi my blogger, your website is really filled with good subjects, but what the aspx finishing of each site symbolizes? I only know php. Is aspx critical?

Bankers Lamps United States

Monday, May 03, 2010 5:25 AM

Bankers Lamps

Wow, I have a blog too but I can't write as well as you do. Good stuff.

Consignment United States

Friday, May 07, 2010 4:44 PM

Consignment

Nice one, there is actually some great facts on this post some of my subscribers may find this useful, will send them a link, many thanks.

flat 2 rent kingston upon thames Costa Rica

Monday, May 10, 2010 3:52 AM

flat 2 rent kingston upon thames

For starters allow me to thank you for this particular information it's not at all often you discover a blog post that's well prepared and also useful I have been seeking information regarding this subject for a really lengthy period. Flat to rent Kingston upon thames

customer relationship management Singapore

Monday, May 10, 2010 6:46 AM

customer relationship management

this subject This excellent information is particularly beautifully composed, and in addition it possesses many informative things. My partner and i treasured the professional  crafting your blog. You have in effect made this simple and easy  so I will be able to fully understand.

vga to svideo United States

Wednesday, May 12, 2010 11:43 AM

vga to svideo

I can see that you are putting a lot of time and effort into your blog and detailed articles! I enjoy deeply excited about every single bit of details you post here (you can find not numerous quality blogs left .

VIRGINIA MCINTOSH United States

Monday, May 17, 2010 8:26 PM

VIRGINIA MCINTOSH

hello great website yea nice job our review blog will soon be adding reviews on blogs and add them to our websites as the top best 50 blogs to visit we also do reviews on Product Reviews  all types of reviews we will get back to you

Modern Warfare 2 United States

Thursday, May 20, 2010 7:25 AM

Modern Warfare 2

Man, that is without question some quality information!  I have a single query intended for you - precisely how long did it take you to be able to formulate this specific post?  In either case, I am just a seriously big enthusiast of Modern Warfare 2 and I appreciated your post a good deal!  Have you heard of this excellent website generally known as Modern Warfare 2 Central Command? I think you actually need to help make a post with regards to it considering you would probably have a handful of crucial things to announce :)I praise you for a second time regarding this post and make sure you take into consideration everything that I claimed concerning Modern Warfare 2 Central Command!

free ads France

Sunday, May 23, 2010 11:24 AM

free ads

this is one great blog post,keep going the great job,
i subscribed to your feed by the way...

Johnny Rocker United States

Monday, May 31, 2010 7:28 PM

Johnny Rocker

Great blog post but, have your ever thought of maybe adding some more images to go along with your great writting skills? I think it might keep more of your readers interested. I'll check back shortly.

George Martyn United States

Thursday, June 03, 2010 5:09 PM

George Martyn

Loved the article, plenty of great advice. When it comes to hosting a wedding, my advice is to shop around a bit.

lab0rat United States

Friday, June 04, 2010 4:54 AM

lab0rat

I agree, mostly, but don't you feel you're oversimplifying?

Angie United States

Friday, June 04, 2010 4:36 PM

Angie

You get the Lynx alpha yet? I'm wondering if I should install it, want to hear any thoughts

Larae Pickel United States

Monday, June 07, 2010 10:10 AM

Larae Pickel

I'm glad I found this web page, I couldnt obtain any knowledge on this matter before. I also manage a niche site and for anyone who is ever interested in doing some visitor writing for me please feel free to let me know, i'm always look for people to check out my weblog. Please stop by and leave a comment sometime!

Normand Lougheed France

Tuesday, June 08, 2010 10:53 AM

Normand Lougheed

Bonjour, je me souviens rarement de mes <a href="http://www.interpretation-des-reves.com/">rêves</a>, mais la dernière fois je <a href="http://www.interpretation-des-reves.com/interpretation-dun-reve/interprtation-du-rve-alphabet/" title="Interprétation du rêve : alphabet">rêvai que je lisais l'alphabet</a> je ne sais pas ce que cela signifie.pouvez-vous m'aider.

free movies online to watch United States

Thursday, June 10, 2010 8:02 PM

free movies online to watch

Hey. This is a very good weblog. You have done a good work! Congrats :)

free movies online to watch United States

Friday, June 11, 2010 12:07 AM

free movies online to watch

Hello. This is a very nice webpage. You actually made a superb job! Best wishes :))

kids discos wiltshire United States

Friday, June 11, 2010 5:00 PM

kids discos wiltshire

I'm not 100% on this, but I do like the idea. I think you'll find a lot of people will agree with you here.

Business Web Directory United States

Friday, June 11, 2010 10:15 PM

Business Web Directory

Quite Wonderful Blogpost. Would you mind if I take a tiny snippets of the write-up and needless to say link it for your blogposts??

Tom United States

Saturday, June 12, 2010 11:37 AM

Tom

lol, I really think I get this. 100% with you here. Some might disagree, but don't listen to them!

Reginald Ackison United States

Saturday, June 12, 2010 4:16 PM

Reginald Ackison

Where was that sexy hot babe http://hotmilf.ws/index.shtml when I was young? I'm the same age at present 'n that really takes some of the enjoyment out of the experience, lol!

Job's and Career United States

Saturday, June 12, 2010 10:41 PM

Job's and Career

Ok, I just found your blog. I used to be a food blogger myself so I can say that your recipes put mine to shame. You rock!

Bob Schmidt United States

Sunday, June 13, 2010 9:33 AM

Bob Schmidt

Hey - Alpha Girl Here!  I just found your blog and absolutely love it!  I linked to it from my site and will be back often.  Thanks!

Olen Reveles United States

Sunday, June 13, 2010 12:03 PM

Olen Reveles

Hey there!  I'm so jazzed about the new season of True Blood!

Season 3 is finally on the air and I am really wound up.

True Blood is the best show on television!

Tom @ Web Design Surrey United States

Sunday, June 13, 2010 4:09 PM

Tom @ Web Design Surrey

Ha, Not sure everyone will get this but I pretty much agree with you.

Unlimited linux hosting United States

Monday, June 14, 2010 9:46 AM

Unlimited linux hosting

Greetings! First of all I would like to say that your blog really helped me in saving time and effort searching for info on google. I would also like to recommend a cool webhost for anyone wanting to blog. Just see my link for details and don't forget to use the student friendly discounts by using STUHST4U as the coupon code.

Condos United States

Monday, June 14, 2010 11:47 PM

Condos

This article about condo provides the light in which we can observe the reality. this is very good one and provides in depth info. thanks for this nice article Great publish..
..
.Valuable information for all.I will suggest my close friends to read this for sure

Deeann Marsden United States

Wednesday, June 16, 2010 1:38 AM

Deeann Marsden

Thanks for this great post.This is first time on this website and really found it very awareness-raising.

drink water for health United States

Wednesday, June 16, 2010 1:13 PM

drink water for health

Wow, this is so inspiring. Everyone should always be looking to better themselves. This really helps.

security hereford United States

Wednesday, June 16, 2010 4:30 PM

security hereford

Everyone should always be looking to better themselves. This really helps.

Laraine Toh United States

Wednesday, June 16, 2010 10:10 PM

Laraine Toh

I just attempted to grab the RSS Feed to this blogsite but it is not properly showing up in Google Chrome. Does anyone have any suggestions?

Hot Belize

Friday, June 18, 2010 2:16 AM

Hot

Akiba-Idols is really a site specialized in the actual craze that was going on within Japan;Idols. Idols tend to be scantily clad lady or actually ladies (jr . idols) appearing upon screen in inciteful poses, expressions and maybe actually situations. Be aware that it's not exactly porn, but maybe really a gentle type of porn that requires no full bare skin no penetration in any way. Updates tend to be weekly as well as can include Intravenous as well as Junior idols. Check us out at Akiba-Idols.com

tv on internet United States

Saturday, June 19, 2010 5:15 AM

tv on internet

I just expect to have understood this the way it was destined

photo shop element United States

Tuesday, June 22, 2010 4:29 PM

photo shop element

A strong imagination begetteth opportunity. Michel de Montaigne

Bacterial Vaginosis Natural Treatments United States

Tuesday, June 22, 2010 9:52 PM

Bacterial Vaginosis Natural Treatments

Impressive article, lots of great info.  I am going to point out to my friends and ask them what they think.

bipasha jain United States

Wednesday, June 23, 2010 2:27 AM

bipasha jain

nice post.you have nicely covered this topic.

classic car classifieds United States

Wednesday, June 23, 2010 2:57 AM

classic car classifieds

Thanks for this insightful post. The info I have gained from your blog is truly inspiring

Ronni Goo United States

Thursday, June 24, 2010 12:16 AM

Ronni Goo

Here is the second time I have come across your web site within the last few weeks.  Looks like I ought to take note of it.

moco poco United States

Thursday, June 24, 2010 1:37 PM

moco poco

Hi this is my first visit on this site, I Love! the images :P

FileMaker Hosting Germany

Friday, July 09, 2010 8:04 AM

FileMaker Hosting

Superb Blog, thanks for helping me with your fine Article. I think it is really a great topic to write about on my Site. Also here is some good information if needed: <A href="http://www.pointinspace.com">FileMaker Hosting</A>

chicago flat fee mls listing United States

Monday, July 19, 2010 6:40 AM

chicago flat fee mls listing

Howdy,

I wanted to say that I have been reading for a few days and I would like to sign up for the rss feed. Regrettably, I am not to savy so I'll give it a try but I will need some assistance. This is a good find and I would hate to lose contact, and maybe never discover it again.

Anyway, thanks again and I look forward to posting again sometime!

Virility Ex Where to Buy United States

Tuesday, July 27, 2010 4:53 PM

Virility Ex Where to Buy

I differ with most people here; I started reading this post I couldn't stop until , while it wasn't just what I had been trying to find, was indeed a fantastic read though. I will instantaneously grab your blog feed to keep in touch of any updates.

zosivacky United States

Thursday, July 29, 2010 8:35 AM

zosivacky

Thank you for this wonderful posts. Really made my spare time one pleasant experience.

Attic Boy United States

Wednesday, August 04, 2010 4:27 PM

Attic Boy

This is like my fifth visit to your blog - I really like the content on your site.  Do you mind If I use it on my own blog?  (With a link back of course...)

Job - MazatlanFishingReport United States

Monday, August 09, 2010 2:59 AM

Job - MazatlanFishingReport

First of All i want to thank you for this nice fishing website!, i been reading few times and now is on my Favorites.
I hope some day sign again in your comments, and keep the effort of keeping this Page updated as i keep my site of http://www.mazatlanfishingreport.com
My home country is Mexico specific in Mazatlan, the sailfish & mahi mahi Capital, and i want to invite everyone to visit our Country. also if you have time for Mazatlan Sport Fishing you will be impressed about our fishing action.
Let me know if you like to post articles about our great mazatlan fishing, in your site.
thank you and keep tight lines.
Job O.
http://www.mazatlanfishingreport.com

gelosia Uruguay

Friday, August 13, 2010 5:37 AM

gelosia

Many thanks for this brilliant post.

restaurant city tips United States

Sunday, August 15, 2010 7:36 PM

restaurant city tips

Hey, I just found this article through Google. I enjoy the rating affirmed by the article. I'm going to subscribe to your feeds aiming to like again. Please if you guys can look up my blog, HackingEdge.com.

home inspection nightmare United States

Sunday, August 15, 2010 9:08 PM

home inspection nightmare

Hi! I saw your blog at Google and have learned a lot from it. Thank you very much for the useful and detailed posts. Will be coming back soon.

Add comment


(Will show your Gravatar icon)

  Country flag


  • Comment
  • Preview
Loading