Sorin Comanescu
Sorin Comanescu

Reputation: 4867

Is it possible to know if a JPEG image was rotated only from its raw bytes?

Can you tell (let's say using .NET 4.0, WinForms) if a JPEG image is rotated only from its binary (like the result of File.ReadAllBytes())?

UPDATE


Thank you all for your answers so far.

Just a heads-up for anybody trying to solve the same problem. I was tricked by the System.Drawing.Image class, which loads the EXIF tags when initialized with FromFile(...) but seems to ignore them when initialized from a stream. I was using the ExifTagCollection library to read the EXIF tags but I guess the results would be comparable with any other lib.

var bytes = (get binary from server)
File.WriteAllBytes(path, bytes);

WORKS:

var image = Image.FromFile(path);

DOES NOT WORK: (fails for FileStream too)

using (var ms = new MemoryStream(bytes))
{
    image = Image.FromStream(ms);
}

Continued with:

ExifTagCollection exif = new ExifTagCollection(image);
foreach (ExifTag tag in exif)
{
    Console.WriteLine(tag.ToString());
}

there are no tags if loading from stream.

Upvotes: 4

Views: 7213

Answers (4)

Jon Hanna
Jon Hanna

Reputation: 113392

http://jpegclub.org/exif_orientation.html details the exif orientation flag. Find that, find the orientation.

Of course, this only applies to rotating an image by setting that flag, as is often done by cameras themselves, some image-viewing software that isn't designed for more detailed editing, and some straight-from-the-file-manager tools. It won't work if someone loaded the image into a more general image-editor, turned it around, and then saved it.

Edit:

Landscape vs. Portrait is different to "rotated from image-devices natural orientation". It's also simpler:

if(img.Height == img.Width)
  return MyAspectEnum.Square;
if(img.Height > img.Width)
  return MyAspectEnum.Portrait;
return MyAspectEnum.Landscape;

That may be closer to what you really want to know about.

Upvotes: 5

It is necessary to read the EXIF to determite the JPEG image orientation.

Please take a look at the ExifLib - A Fast Exif Data Extractor for .NET 2.0+. It seems the library returns the Orientation like specified here.

Upvotes: 1

Alex
Alex

Reputation: 23290

In case EXIF data is not available / not reliable you might assume this to identify a picture format:

  • Height > Width ? Portrait format
  • Width > Height ? Landscape format
  • Width = height ? Picture is perfectly square, either one is fine

Same restriction as EXIF applies: a physical editing which turned around the picture and didn't update/set EXIF info accordingly will fool this check too.

Upvotes: 2

Navaneeth K N
Navaneeth K N

Reputation: 15541

If you know how to read the JPEG encoded data, you could look for the EXIF and get the rotation from EXIF. It would be tough if EXIF data is not available.

Upvotes: 1

Related Questions