Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 351
Sorin Comanescu Avatar asked Jan 15 '23 20:01

Sorin Comanescu


2 Answers

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.

like image 191
Jon Hanna Avatar answered Jan 23 '23 03:01

Jon Hanna


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.

like image 32
Alex Avatar answered Jan 23 '23 03:01

Alex