Exif Properties in .Net - Part 1 : (fast) loading

In .Net, handling a picture's Exif properties seems, at first sight, to be a very simple job.

Since System.Drawing is only a wrapper around GDI+, loading Exif information from an image file is as simple as the following :

Code Copy
public static PropertyItem[] GetExifProperties(string fileName) {
using(Image image = Image.FromFile(fileName))
return image.PropertyItems;
}

Unfortunately, this method requires to load - and validate - all image data in order to access the Exif properties. For instance, if you want to retrieve the thumbnail contained in the Exif properties, you first have to load and uncompress the entire image file.

This problem has been workarounded in the .Net Framework 1.1 Service Pack 1, and now you can process as follow :

Code Copy
public static PropertyItem[] GetExifProperties(string fileName) {
using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
using (Image image = Image.FromStream(stream,
/* useEmbeddedColorManagement = */ true,
/* validateImageData = */ false))
return image.PropertyItems;
}

However, since there is only a small share of PixVillage users that have the .Net Framework 1.1 Service Pack 1 installed, I eventually have implemented a custom ExifLoader helper class that use Interop to load Exif properties.

The first step is to load the image using the GDI+ Flat API and get the Exif properties raw data :

Code Copy HideScrollFull
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;

/// <summary>
///
Contains helper methods for loading Exif properties.
/// </summary>
public sealed class ExifLoader {
private ExifLoader() {}
/// <summary>
/// Retrieves Exif properties from a file.
/// </summary>
/// <param name="fileName">The name of the Exif image file.</param>
/// <returns>An array of <see cref="PropertyItem"/> objects containing the Exif properties.</returns>
public static PropertyItem[] GetExifProperties(string fileName) {
// Loads the image file using the GDI+ Flat API
IntPtr imageHandle = IntPtr.Zero;
if (GdipLoadImageFromFile(fileName, out imageHandle)!=0)
throw new InvalidOperationException();
int count;
int totalSize;
IntPtr data = IntPtr.Zero;

try {
// Retrieves the number of properties the image contains
if (GdipGetPropertyCount(imageHandle, out count)!=0)
throw new InvalidOperationException();
// Gets the total size, in bytes, of the properties
if (GdipGetPropertySize(imageHandle, out totalSize, ref count)!=0)
throw new InvalidOperationException();
// There is no available properties...
if (count == 0 || totalSize == 0)
return new PropertyItem[0];
// Loads all properties into memory.
data = Marshal.AllocHGlobal(totalSize);
if (GdipGetAllPropertyItems(imageHandle, totalSize, count, data)!=0)
throw new InvalidOperationException();
// Convert the properties buffer into an array of PropertyItem objects.
return ExifPropertyItem.ConvertFromMemory(data, count);
}
finally {
if (data != IntPtr.Zero)
Marshal.FreeHGlobal(data);
// Releases the GDI+ image.
GdipDisposeImage(imageHandle);
}
}

ExifPropertyItem Helper Class

// GDI+ Interop
[DllImport("gdiplus.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
private static extern int GdipLoadImageFromFile(string filename, out IntPtr image);

[DllImport("gdiplus.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
private static extern int GdipDisposeImage(IntPtr image);

[DllImport("gdiplus.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
private static extern int GdipGetPropertyCount(IntPtr image, out int count);

[DllImport("gdiplus.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
private static extern int GdipGetPropertySize(IntPtr image, out int totalSize, ref int count);

[DllImport("gdiplus.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
private static extern int GdipGetAllPropertyItems(IntPtr image, int totalSize, int count, IntPtr buffer);
}
. . .

Then, we have to decode the buffer filled by GdipGetAllPropertyItems. This is done using a private inner class, as follow :

Code Copy HideScrollFull
#region ExifPropertyItem Helper Class

/// <summary>
///
Represents an helper class for marshaling Exif property items.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private class ExifPropertyItem {

// Public members used for marshaling.
public int id = 0;
public int len = 0;
public short type = 0;
public IntPtr value = IntPtr.Zero;

/// <summary>
/// Initializes a new instance of the <see cref="ExifPropertyItem"/> class.
/// </summary>
/// <remarks>Used only by the <see cref="Marshal.PtrToStructure"/> method.</remarks>
public ExifPropertyItem() {}

/// <summary>
/// Gets the value of the property.
/// </summary>
public byte[] Value {
get {
byte[] buffer = new byte[len];
if (len > 0)
Marshal.Copy(value, buffer, 0, len);
return buffer;
}
}

/// <summary>
/// Converts a buffer into an array of PropertyItem objects.
/// </summary>
/// <param name="propertyData">The properties data buffer.</param>
/// <param name="count">The number of properties in the buffer.</param>
/// <returns>An array of <see cref="PropertyItem"/> objects.</returns>
public static PropertyItem[] ConvertFromMemory(IntPtr propertyData, int count) {
PropertyItem[] itemArray = new PropertyItem[count];
for (int i = 0; i < count; i++) {
// Marshals the buffer into a ExifPropertyItem structure.
ExifPropertyItem item = (ExifPropertyItem)Marshal.PtrToStructure(propertyData, typeof(ExifPropertyItem));

// Creates the PropertyItem from the data.
itemArray[i] = Create(item.type,  item.id, item.len, item.Value);

// Seek to next property.
propertyData = (IntPtr)(((long)propertyData) + Marshal.SizeOf(typeof(ExifPropertyItem)));
}

return itemArray;
}

/// <summary>
/// Creates a PropertyItem from its components.
/// </summary>
/// <param name="type">The property type.</param>
/// <param name="tag">The property tag.</param>
/// <param name="len">The length of the property.</param>
/// <param name="value">The property value.</param>
/// <returns></returns>
private static PropertyItem Create(short type, int tag, int len, byte[] value){
PropertyItem item;

// Loads a PropertyItem from a Jpeg image stored in the assembly as a resource.
Assembly assembly = Assembly.GetExecutingAssembly();
using(Stream emptyBitmapStream = assembly.GetManifestResourceStream("ExifLoader.empty.jpg"))
using(Image empty = Image.FromStream(emptyBitmapStream))
item = empty.PropertyItems[0];
// Copies the data to the property item.
item.Type = type;
item.Len = len;
item.Id = tag;
item.Value = new byte[value.Length];
value.CopyTo(item.Value, 0);

return item;
}
}

#endregion
. . .

Note that in the class above, we load a jpeg file from resources into memory. This file is named "empty.jpg" but the resource is referenced as "ExifLoader.empty.jpg" since "ExifLoader" is the name of the assembly.

Since the PropertyItem class does not provide a public initializer to create a property "from scratch", we have to use an existing property item.

posted on Thursday, March 17, 2005 11:51 AM

Feedback

# re: Exif Properties in .Net - Part 1 : (fast) loading 5/31/2005 10:00 PM MrPolite

THANK YOU!!!!!!!!!!
life savor! I've been searching for this forever

# re: Exif Properties in .Net - Part 1 : (fast) loading 9/13/2005 5:34 PM Christoph Neyen

Very Good!!!

But, how can i create this empty jpg with an empty tag?

Or, is it possible to download it?

# re: Exif Properties in .Net - Part 1 : (fast) loading 3/26/2006 6:27 PM Pynosol

Excellent!

# plus dresses 7/27/2011 2:44 AM plus dresses

http://www.haswatches.com">http://www.haswatches.com replica watches
http://www.haswatches.com">http://www.haswatches.com fake watches
http://www.haswatches.com">http://www.haswatches.com/Rolex.html replica rolex watches
http://www.haswatches.com">http://www.haswatches.com/Rolex.html rolex replica

# re: Exif Properties in .Net - Part 1 : (fast) loading 8/27/2011 7:50 AM fake watches

In this modern and fashionable society, people are pursuing for <a href="http://www.watchreplicasale.com">Replica Watches</a> cool, unique, stylish and innovative. Whether it is <a href="http://www.replicaswatchsale.com">watch replica</a> or fashion accessories all means a lot for modern society of today. Same is the case with trendy looking <a href="http://www.watchesfame.com">Replica Watches</a>. When these are <a href="http://www.watchreplicasale.com">watch replica</a>, the excitement just gets doubled. Most chic looking <a href="http://www.replicaswatchsale.com">Replica Watches</a> are in fashion now. These are one of the favorite fashion accessories for men and women long time ago. If you have not yet tried <a href="http://www.watchesfame.com">watch replica</a>, it's time to own one and feel the difference it can make to your personality. These are just brilliant and fabulous <a href="http://www.watchreplicasale.com/">replica watches swiss made</a>. They are most iconic and can provide you with a new feeling and enhance confidence. The quality of <a href="http://www.replicaswatchsale.com/">best replica watches</a> is just superior to what you have dreamt of. Today owning a new and trendy looking <a href="http://www.watchesfame.com/">replica swiss watches</a> are not only meant for the wealthy people. These are now made luxurious and affordable <a href="http://www.watchreplicasale.com/">wholesale replica watches</a> to reach out to every budget and range. You can just enjoy them by ordering <a href="http://www.replicaswatchsale.com/breitling.html">replica breitling watches</a> online where you get the complete satisfaction and genuine quality at best possible rates. The finish, quality and designs you get from <a href="http://www.watchesfame.com/breitling">breitling replica watches</a> are really astonishing and you will love them all. Different styles and designs of <a href="http://www.replicaswatchsale.com">replica">http://www.replicaswatchsale.com">replica watches swiss made</a> are now available to make your wrist beautiful. You can choose from the wide variety of <a href="http://www.watchesfame.com">best replica watches</a> by comparing lots of perfect and stunning pieces. These <a href="http://www.watchreplicasale.com">replica swiss watches</a> would be nice investments for you in long term. These <a href="http://www.replicaswatchsale.com">wholesale replica watches</a> are brilliant and prove to be wonderful for you while it makes you stand out of the crowd. The dashing and extraordinary <a href="http://www.watchesfame.com/breitling">replica breitling watches</a> you get will attract every eye in a crowd and makes you feel more confident. If you are not having <a href="http://www.watchreplicasale.com/breitling-c-105.html">breitling replica watches</a> yet, check them out and own them now as were not so affordable ever before. You will not miss them out. Be it Christmas or Valentine's Day or any other special day that you would like to celebrate, a <a href="http://www.watchesfame.com">replica watches swiss made</a> gift would be just perfect for any occasion. Many people think of the perfect <a href="http://www.watchreplicasale.com">best replica watches</a> to purchase for their loved ones. Even if you shop for your special occasion at the last moment, you are sure to find something nice at <a href="http://www.replicaswatchsale.com">replica">http://www.replicaswatchsale.com">replica swiss watches</a>. <a href="http://www.watchesfame.com">wholesale replica watches</a> gifts are not restricted to just your lover, you could also pick perfect for almost everyone, including your family and friends. What is so extraordinary and unusual when it comes to <a href="http://www.watchreplicasale.com/breitling-c-105.html">replica breitling watches</a> is that you have an option to pick and select your own to be attached onto the of your preference. Just in the range of <a href="http://www.replicaswatchsale.com/breitling.html">breitling replica watches</a>, it provides options of a standard or you could opt for the obsidian. Once you select the bracelet, then you select the charms to be supplemented onto the bracelet.

# re: Exif Properties in .Net - Part 1 : (fast) loading 9/28/2011 8:57 AM valueblog

"That's awesome.
I'm so glad you started blogging and that I can call you my friend.
Keep posting and I'll keep reading."

# re: Exif Properties in .Net - Part 1 : (fast) loading 10/20/2011 11:10 AM JohnKwan

you'll undoubtedly find a pair of <a href="http://www.replicawatchesbest.net/emporio-armani-watches-c-47.html"> emporio armani watches </a> or <a href="http://www.replicawatchesbest.net/ebel-watches-c-112.html"> ebel watches </a> or <a href="http://www.replicawatchesbest.net/dolcegabbana-watches-c-45.html"> Dolce&Gabbana Watches </a> or <a href="http://www.replicawatchesbest.net/dior-watches-c-111.html"> dior watches </a> that suits you.

# re: Exif Properties in .Net - Part 1 : (fast) loading 10/31/2011 7:45 AM Bailey Button Triplet

you'll undoubtedly find a pair of <a href="http://www.baileybuttontriplet.ws/">">http://www.baileybuttontriplet.ws/"> UGG Bailey Button </a> or <a href="http://www.baileybuttontriplet.ws/">">http://www.baileybuttontriplet.ws/"> Bailey Button Triplet </a> that suits you.

# re: Exif Properties in .Net - Part 1 : (fast) loading 11/7/2011 10:18 AM cheap Uggs

you'll undoubtedly find a pair of <a href="http://www.cheapuggsbox.com/ugg-roxy-tall-5818-c-11.html"> ugg roxy tall </a> or <a href="http://www.cheapuggsbox.com/"> cheap Uggs </a> that suits you.

# Jam Tangan 11/24/2011 3:02 AM Jam Tangan


[url=http://www.jamreplika.com">http://www.jamreplika.com">http://www.jamreplika.com">http://www.jamreplika.com]Jam Replika[/url]
[url=http://www.jamreplika.com">http://www.jamreplika.com">http://www.jamreplika.com">http://www.jamreplika.com]Jam Tangan Replika[/url]
[url=http://www.jamreplika.com">http://www.jamreplika.com">http://www.jamreplika.com">http://www.jamreplika.com]Jam Tangan[/url]

# Mackenzie 12/29/2011 2:37 AM tall christian louboutin

http://www.varyshoes.com/fashion-collection.html red heels they are able to be ready to seize the most effective photos of the occasion The 26 yr previous singer married Sam Cooper in Gloucestershire in the weekend and has switched her profile from Lily Rose Allen to Mrs LR Cooper Lily Allen modifications surname on Twitter to match husband Lily Allen has altered her title on Twitter to Lily Cooper The 26 yr outdated singer married Sam Cooper in Gloucestershire in the weekend and has switched her profile from Lily Rose Allen to Mrs LR Cooper http://www.varyshoes.com/sandals.html leather sandals The few tied the knot at St James the Wonderful Church in Cranham close to Stroud on Saturday She tweeted <img src="http://www.varyshoes.com/images/uploads/short_boots/CLSS-pump006.jpg" http://www.varyshoes.com/christian-louboutin-bow-sandals-in-black-651-lady.html bow sandals in black "I had by far the most incredible wedding ceremony http://www.varyshoes.com/christian-louboutin-gold-high-heels-610-lady.html gold high heels thanks to everybody who went to this kind of extraordinary attempts to create it that way" It was also unveiled on her wedding ceremony day which the singer was pregnant immediately after she was photographed having a

# Mackenzie 12/29/2011 2:43 AM replica watches for sale

calculators regardless of to become timekeeping appliances http://www.samewatches.com/Stainless-Steel-Blue-Dial-Arabic-Hour-markers-II-171336-gift.html">http://www.samewatches.com/Stainless-Steel-Blue-Dial-Arabic-Hour-markers-II-171336-gift.html replica rolex Explorer Some abilities perhaps electronic digicam keep track of process chronograph too as an capability maintain up from fantastic shock regular h2o and furthermore harm you might also have noticed inducted in the modernday appreciate style http://www.samewatches.com/Rolex-Datejusts.html">http://www.samewatches.com/Rolex-Datejusts.html rolex classic women fake http://www.samewatches.com replica watches for sale The market for fashionable have a look at leaders related to Polanti watches Von Nederlander watches collectively with Giantto watches is rising mainly because market monetary program acquires traction by indicates of every single transferring previous thirty day period after which you will discover adequate perform with presume this method advancement may well nicely nonetheless stick towards the precise very same course for a long time inside the long term at this Using the technologies about personal computer study http://www.samewatches.com/Breitling-Chronometer-Navitimer-Chronograph-Stainless-Steel-2472-gift.html Speedmaster omega globalization at the same time as ecommerce http://www.samewatches.com/Navitimer-125E-Chronograph-silver-SS-case-silver-luminescent-m-24225-gift.html best replica Breitling watch http://www.samewatches.com/Porsche-Design.html fake Porsche Design

# re: Exif Properties in .Net - Part 1 : (fast) loading 1/5/2012 8:40 AM replica watches

replica watches
http://www.cheapwatchmart.com/
cheap rolex watches
http://www.cheapwatchmart.com/rolex-watches.html
Breitling Watches
http://www.cheapwatchmart.com/breitling-watches.html
Omega Watches
http://www.cheapwatchmart.com/omega-watches.html

# louis vuitton sale 2/1/2012 3:30 AM louis vuitton sale

Bags of many different models, materials and colors at the
louis vuitton sale

outlet can be significant along with ample, nevertheless quite trendy, fantastic requirement.Here is a world of
louis vuitton outlet

where you can find all kinds of new style and fashion Louis Vuitton bags. We really want to lead the trend and let our customer in the pursuit of luxury and fashion, satisfied the needs of customers.

# coach factory outlet 2/1/2012 5:54 AM coach factory outlet

If you do not know design can be the most fashionable this fall, consider a glance on
coach factory outlet

! This summer, you have a wide range of options, because there are numerous designs, you can find from.
coach factory online

is actually a stylish Coach online store to sell perfect quality and discount Coach handbags, Coach bags, Coach wallets and Cheap Coach Purse.If you love Coach,you will like to get the best price on it.

# christian louboutin uk 2/1/2012 5:55 AM christian louboutin uk

If you have enough leisure time, you may go to the mall or go to the christian franchised store to have a good look at varieties of
christian louboutin uk

the diverse styles and rich colors of the purses with low cost will surely impress you a lot!You will always get surprised by the beautiful colors and perfect details of
christian louboutin

.So come on, do not hesitate.

# coach bags 2/1/2012 10:04 AM coach bags

coach bags

with fashion style and top quality succeed. In any occasions they are very suitable and appropriate for its precise and rich design.
coach outlet store

vision system is a visual enjoy, is a visual art. The particular design has been integrated function and the element of elegancy, then show you an exquisite and excellent product.

# coach outlet online 2/2/2012 1:39 AM coach outlet online

Becoming a regular member of
coach outlet online

, you can even buy wholesale purses, handbags, leather wallets at preferential prices. Why not have a try?
coach factory outlet

is famous for the discounts it offers. Latest coach purses and sunglasses can be purchased at discounted rates from this coach outlet store.
http://www.coachoutletonlinecoachdays.com

# coach outlet 2/2/2012 2:00 AM coach outlet

coach outlet

sells products which are excellent in quality and reasonable in price. All customers can easily pick up their favorite Coach briefcase, wallets, shoes, hats, scarf, jewelry and sunglasses.If you need to acquire the focus, you need to sustain the
coach outlet store online

, which with stylish components that will immediately concoct you appreciably more attracting and outstanding.
http://www.coachoutletcoachstore.com

# chanel uk 2/2/2012 2:01 AM chanel uk

Swarovski's Crystal is due to their commitment to consistency, precision and quality standards, and to the automatic cutting machine invented by the founder,
chanel bags

enjoy high reputation all over the world. They are designed for hand, elbow and shoulder carry thanks to comfortable flat leather handles.
http://www.chanel-outlet.org.uk

# coach factory outlet 2/2/2012 2:26 AM coach factory outlet

That experts claim coach factory outlet shopping is in the changes they are available in, which can make it well suited for benefit from to be a'luggage'bag. There are different kinds of crossbody bags within marketplace nowadays. Even so it is not possible to beat the timeless design jointly with traditional elegance of the Bags at the coach factory outlet online.
http://www.coachfactoryoutletonlinedays.com

# louis vuitton uk 2/2/2012 2:26 AM louis vuitton uk

More and more people can afford louis vuitton uk, not to say they are on sale. Price is not equivalent with value,they own classical style, fine materials, elaborate technique. If you want to catch up to the latest vogue, having Louis Vuitton Handbags of the latest styles can absolutely satisfy you.Just visit LV outlet webpage and select the most suitable products for yourself.
http://www.louisvuitton-full.org.uk

# christian louboutin 2/2/2012 2:26 AM christian louboutin

This elegant and discreet pair of rhodium-plated button christian louboutin will add sparkle to your outfit. They are covered in clear crystal pave and reflect the light in magical ways. christian Madison Handbags and christian Poppy Bags are viewed among probably the most newsworthy among the particular christian louboutin uk so far.
http://www.christian-louboutinshoes.co.uk

# coach outlet online 2/2/2012 2:32 AM coach outlet online

If you buy Coach items at the
coach outlet online

store, the goods will be sent out within 24 hours after confirming your payment and arrive to your door within 7 work days.
coach outlet

can provide the coach exactly the same is expected in a retail store. It can help you find bags of various colors, shapes and designs, which prove once again that the coach is actually a selection for the housekeeper.
http://www.coachoutletonlinecell.com

# chanel uk 2/2/2012 2:38 AM chanel uk

chanel uk have own characteristic designs. The beautiful crystals have added the magical finishing touch to countless bridal gowns. Just get some for yourself. I hope that I have helped you realize the potential for a breathtaking theme on your wedding day.Incorporating chanel handbags and pearls into your decor is a very fun and easy way to create a classic and warm setting.

http://www.chanel-bags.org.uk

# coach outlet store 2/2/2012 2:38 AM coach outlet store

Coach Outlet Store sells goods that are constructed to meet the highest standards of quality and functionality.You can trust it 100 percent. Wholesale coach outlet are even provided for VIP members. Haven't got your own Coach yet? Why not come to coach outlet store online outlet.

http://www.coachoutletstoreonlinegood.com

# coach outlet online 2/2/2012 2:38 AM coach outlet online

I got to know it from my elder sister who owns enviable luxury Coach bags. Coach Outlet Online Store is established to be your home shopping paradise. Coach New Signature BackPack Black Beige is a useful backpack for outdoors activities. It's convenient that you can freely take along with for travel,climbing and go for school.In our coach outlet,there are many graceful styles of Coach backpack for you.

http://www.coachoutletonlinefull.com

# louis vuitton uk 2/2/2012 4:02 AM louis vuitton uk

This
louis vuitton uk

for sale belongs to the sounding just what are termed as Louis Vuitton vintage best sellers, many other products and services for the reason that range appearing companies.I am so confused that I don,t even know where to buy the
louis vuitton

Handbags. Because I can prefer to chose the fashionable design, favorable price, top service .
http://www.louis-vuittonukoutlets.org.uk

# louboutin uk 2/2/2012 4:09 AM louboutin uk

Come by for dinner soon and check out the wine list for yourself. We are always here to help with selection. Cheers for the successful of christian
louboutin uk

.The christian Signature Hobo is from the latest release of
christian louboutin uk

. Its crisp, scribble material, leather handle, perfectly complements the relaxed shape of this stylish pouch.
http://www.christianlouboutinuk-sale.co.uk

Title
 
Name
 
Url
Comments   
Protected by Clearscreen.SharpHIPEnter the code you see: