PHOTOS & EXIF DATA

A client had raised a case at work because some of the photos that they had taken were not in the correct orientation on a webpage. Or, as they had put it, "all of my photos are sideways!" This eventually boiled down to our program not sifting through the masses of metadata attached to each photograph uploaded and making some sort of assumption about how the user wants to view it.

Alright, so I've got access to the filepaths where these photos are stored, lending me access to all the raw data I need. Without mangling the client's original data, how do I do this? At my job I work with a few languages, but for this one I'm dealing with ASP.NET (C# mainly).

Attempt 0001

.NET has inbuilt functionality to read photo metadata so I don't really need to be doing too much in the way of figuring out how to get or manipulate anything. Attempt number one involved me creating a new Image object from a Bitmap object, reading what I needed to, applying the changes I needed to make, and overwriting the original file.

This was slow as fuck, and also permanently changes the original image. What happens if something fails server-side? Shit can get lost. Didn't even bother with speed tests with this one. This was more figuring out what the hell I was supposed to be doing.

Attempt 0010

Let's build off what we had before. Image object from a Bitmap object, but throw this into a method and return an integer denoting the number of degrees we need to rotate an image. Yeah, EXIF orientation can also tell you whether you need to flip an image or not, but who cares about that. Once I have that magic int, I can pass it through to a control and let some JavaScript handle the rest.

This is way better. Original photo is still intact, and this is a lot faster as we can rotate the photo client-side via JavaScript as opposed to the server-side C# mess we had before.

Attempt 0011

After some research I found you could also use Image.FromStream() as opposed to creating a Bitmap object. Already this sounds like we're doing a lot less work. I decided to run a few speed tests on various file sizes to see how long it takes (roughly) to read the data we need.

Without a specialised NuGet package, and for a fix in an ASPX page (as opposed to something more centralised), this is pretty damn good.

[ BACK TO TOP ]