Rectangle 27 5

Please note that there are better answers below.

When a picture is taller than it is wide, it means the camera was rotated. Some cameras can detect this and write that info in the picture's EXIF metadata. Some viewers take note of this metadata and display the image appropriately.

PIL can read the picture's metadata, but it does not write/copy metadata when you save an Image. Consequently, your smart image viewer will not rotate the image as it did before.

Following up on @Ignacio Vazquez-Abrams's comment, you can read the metadata using PIL this way, and rotate if necessary:

import ExifTags
import Image

img =
exif=dict((ExifTags.TAGS[k], v) for k, v in img._getexif().items() if k in ExifTags.TAGS)
if not exif['Orientation']:
    img=img.rotate(90, expand=True)
img.thumbnail((1000,1000), Image.ANTIALIAS), "JPEG")

But be aware that the above code may not work for all cameras.

phatch is a batch photo editor written in Python which can handle/preserve EXIF metadata. You could either use this program to make your thumbnails, or look at its source code to see how to do this in Python. I believe it uses the pyexiv2 to handle the EXIF metadata. pyexiv2 may be able to handle EXIF better than the PIL's ExifTags module.

Or to read the EXIF data beforehand and apply the transformation manually.

Thanks to both of you for your answers. I'm trying to strip all EXIF data, but then add back the data if it has to be rotated. This is turning into much more of a PITA than I originally assumed it would be. Just a matter of working out the script to do it now. Thanks again!

Since you're resizing, you probably don't care, but don't forget that even a simple rotation is sometimes a lossy operation on jpegs.

I upvoted the version that handles all 8 orientations. Also, here's a great set of test images from Dave Perrett.

python - PIL thumbnail is rotating my image? - Stack Overflow

python python-imaging-library
Rectangle 27 0


The only mode accept is r mode (which is default). See here

I have tried it that way, still gives me the same error.

How do you download an image and extract Exif data using Python PIL? -...

python python-imaging-library exif
Rectangle 27 0

You can try loading the image with the Python Image Lirbary (PIL) and then save it again to a different file. That should remove the meta data.

Python: Remove exif info from images - Stack Overflow

python image-processing python-imaging-library exif exiftool
Rectangle 27 0

import Image

image_file = open('image_file.jpeg')
image =

# next 3 lines strip exif
data = list(image.getdata())
image_without_exif =, image.size)

Python: Remove exif info from images - Stack Overflow

python image-processing python-imaging-library exif exiftool
Rectangle 27 0

For listing files in a directory, os.listdir(directory) will get you a list of files AND subdirectories.

files=[os.path.join(directory, f) for f in os.listdir(directory) 
    if os.path.isfile(os.path.join(directory, f))] #Get only files, not directories
for f in files:
  #open file, do EXIF stuff

select directory + extract exif using python - Stack Overflow

python directory exif
Rectangle 27 0

import pyexiv2
from PIL import  Image

file_path = '/home/../img/a.JPG'
metadata = pyexiv2.ImageMetadata(file_path)
thumb = metadata.exif_thumbnail
thumb.write_to_file('512_' + "a")

Now I open the image using Phatch Image Inspector , I can see the exif data

python - Preserve exif data of image with PIL when resize(create thumb...

python python-imaging-library exif
Rectangle 27 0

This depends on the image format heavily. For example, if you have a TIFF file, there is no knowing a priori where the EXIF data, if any, is within the file. It could be right after the header and before the first IFD, but this is unlikely. It could be way after the image data. Chances are it's somewhere in the middle.

If you want the EXIF information, extract that on the server (cache, maybe) and ship that down packaged up nicely instead of demanding client code do that.

Your second paragraph assumes he owns the server storing the images, which might not necessarily be the case :) As for where the EXIF data is located, if I understand this answer correctly, in JPG files the EXIF data will be around the beginning of the file - do you know if this is correct?

Yes, I'm wondering the same myself. Most images are in .jpg, so that would be great.

APP1 section appears after the APP0 section (if it exists). The APP0 marker can be followed by up to 64K of data by the spec, so you should be prepared to handle that. And there may be multiple APP1 sections. Were it me and I was hell-bent on doing this, I'd build a stream solution where I can cut off image delivery at any point (in this case after I have the EXIF, if any).

@plinth How would you build such a stream solution? (ie. the downloading-and-cutting-off-image-delivery-part.)

Get EXIF data without downloading whole image - Python - Stack Overflo...

python image download client-server exif
Rectangle 27 0

You can tell the web server to only send you parts of a file by setting the HTTP range header. See This answer for an example using urllib to partially download a file. So you could download a chunk of e.g. 1000 bytes, check if the exif data is contained in the chunk, and download more if you can't find the exif app1 header or the exif data is incomplete.

Thanks for that, but this is dependent on remote compliance with range header, which is not good enough. Need some way of cancelling curl after x bytes or similar, I'm thinking.

Get EXIF data without downloading whole image - Python - Stack Overflo...

python image download client-server exif
Rectangle 27 0

Every time you read() you move the file pointer. If you want to read the same thing repeatedly (why?) then you can use

to rewind the file pointer to the beginning of the file.

Python reading a .jpg file in binary for beginner - Stack Overflow

python binary jpeg exif
Rectangle 27 0

Developed a simple app in Python but.... the method get_original_metadata() give me always "None" (and i'm sure that the image has Exif, i got this from

Google Appengine Java - Get EXIF data from Image - Stack Overflow

java image google-app-engine exif
Rectangle 27 0

Although PIL can read EXIF metadata, it doesn't have the ability to change it and write it back to an image file.

A better choice is the pyexiv2 library. With this library it's quite simple flip the photo's orientation. Here's an example:

import sys
import pyexiv2

image = pyexiv2.Image(sys.argv[1])

image['Exif.Image.Orientation'] = 6

Actually, the camera already set the Exif.Image.Orientation tag, I want to write the image in the right Orientation to enable browser to display it even if they cannot understand EXIF information. Anyway, pyexiv2 is the library I needed. As you can see in my code behind.

python - How to use PIL to resize and apply rotation EXIF information ...

python jpeg python-imaging-library rotation exif
Rectangle 27 0

You have to use syntax as

metadata['Exif.Image.Copyright']  = pyexiv2.ExifTag('Exif.Image.Copyright', copyrightName)

Note: copyrightName value should be string for "Exif.Image.Copyright"

import pyexiv2
metadata = pyexiv2.ImageMetadata(image_name) 
metadata.modified = True
metadata.writable = os.access(image_name ,os.W_OK)
metadata['Exif.Image.Copyright']  = pyexiv2.ExifTag('Exif.Image.Copyright', 'copyright@youtext') 

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

python - Copying and Writing EXIF information from one image to anothe...

python django
Rectangle 27 0

With pyexiv2 version 0.3, the solution of @user2431382 will not allow to write the EXIF tags to destination_file != source_file. The following version works for me:

m1 = pyexiv2.ImageMetadata( source_filename )
# modify tags ...
# m1['Exif.Image.Key'] = pyexiv2.ExifTag('Exif.Image.Key', 'value')
m1.modified = True # not sure what this is good for
m2 = pyexiv2.metadata.ImageMetadata( destination_filename ) # yes, we need to read the old stuff before we can overwrite it
m1.copy( m2 )

python - Copying and Writing EXIF information from one image to anothe...

python django
Rectangle 27 0

I think the title.human_value data is in UTF-8, having already been decoded from the raw UTF-16 bytes of title.

In the python shell, running in a terminal window on OSX:

>>> # this should be the same as your title.human_value:
>>> print ''.join( chr(x) for x in [208, 156, 208, 184, 208, 
              187, 208, 190, 208, 185, 32, 208, 156, 208, 
              176, 208, 188, 209, 131, 208, 187, 208, 181, 
              32, 208, 190, 209, 130, 32, 208, 156, 208, 
              176, 208, 185, 208, 184, 44, 32, 49, 49, 32, 
              209, 143, 208, 189, 208, 178, 208, 176, 209, 
              128, 209, 143, 32, 49, 57, 52, 52, 46])

   , 11  1944.

Your console may not support Cyrillic characters. You might try setting the font in the Command Prompt to "Lucida Console" -- a more modern vector font is more likely to support it correctly than the historical bitmapped fonts that cmd defaults to.

print u''
, 11  1944.

I don't think it's a Python 2 issue (I'm using Python 2.6), I think it's a terminal encoding issue. At the python prompt, try import sys; print sys.stdout.encoding.


Try setting it to 'utf-8' and printing your string again? I'm not sure how my sys encoding gets set...

I feel myself helpless. I don't know how to set it. Moreover, some functions, mentioned at the help pages (e.g. sys.getdefaultencoding), are not appearing in my Python! Probably, I should first get some Python experience and then return to this issue. In the meantime, I'm using a workaround: display Unicode strings using PyQt.

Python: extract Cyrillic string from EXIF - Stack Overflow

python string unicode encoding exif
Rectangle 27 0

Rotate Image
import pyexiv2
import wx
import cStringIO
import os

def rotateImage(infile, device):
        # Read Metadata from the image
        metadata = pyexiv2.metadata.ImageMetadata(infile);

        # Let's get the orientation
        orientation = metadata.__getitem__("Exif.Image.Orientation")
        orientation = int(str(orientation).split("=")[1][1:-1])

        # Extract thumbnail
        thumb = metadata.exif_thumbnail

        angle = 0

        # Check the orientation field in EXIF and rotate image accordingly
        if device == "iPhone" or device == "iPad":
            # Landscape Left : Do nothing
            if orientation == ORIENTATION_NORMAL:
                angle = 0
            # Portrait Normal : Rotate Right
            elif orientation == ORIENTATION_LEFT:
                angle = -90
            # Landscape Right : Rotate Right Twice
            elif orientation == ORIENTATION_DOWN:
                angle = 180
            # Portrait Upside Down : Rotate Left
            elif orientation == ORIENTATION_RIGHT:
                angle = 90

            # Resetting Exif field to normal
            print "Resetting exif..."
            orientation = 1
            metadata.__setitem__("Exif.Image.Orientation", orientation)

        # Rotate
        if angle != 0:
            # Just rotating the image based on the angle
            print "Rotating image..."
            angle = math.radians(angle)
            img = wx.Image(infile, wx.BITMAP_TYPE_ANY)
            img_centre = wx.Point( img.GetWidth()/2, img.GetHeight()/2 )
            img = img.Rotate( angle, img_centre, True )
            img.SaveFile(infile, wx.BITMAP_TYPE_JPEG)

            # Create a stream out of the thumbnail and rotate it using wx
            # Save the rotated image to a temporary file
            print "Rotating thumbnail..."
            t = wx.EmptyImage(100, 100)
            thumbStream = cStringIO.StringIO(
            t.LoadStream(thumbStream, wx.BITMAP_TYPE_ANY)
            t_centre = wx.Point( t.GetWidth()/2, t.GetHeight()/2 )
            t = t.Rotate( angle, t_centre, True )
            t.SaveFile(infile + ".jpg", wx.BITMAP_TYPE_JPEG)

            # Read the rotated thumbnail and put it back in the rotated image
   = open(infile + ".jpg", "rb").read();
            # Remove temporary file
            os.remove(infile + ".jpg")

        # Write back metadata

    except Exception, e:
        print "Error rotating image... : " + str(e)

ios - Rotating an image with orientation specified in EXIF using Pytho...

python ios image exif
Rectangle 27 0

Not entirely sure, as I've never used this module or played with images, for that matter. Can you not just do something like this? I looked at the documentation and it says that metadata.exif_keys is a list. It seems you would only have to check whether or not the list is empty.

if metadata.exif_keys:

python - Find if an image has EXIF or not - Stack Overflow

python exif pyexiv2
Rectangle 27 0

it is running both on Windows and Ubuntu, and you can get all you need (codec, aspect, fps, bitrate, orientation...).

how to get a video file's orientation in Python - Stack Overflow

python video orientation metadata exif
Rectangle 27 0

I used Python and the Flickr api. I stripped the metadata/exif from the searching image, and stored it. I then used this information store on the image to build a search query that flickr would search for, finding similar images.

This involved taking date and time to limit how many results I got back, and so forth. I purposely made sure any images I wanted to search matches these requirements, along with having some suitable search tags, and an estimated location, specified by the user.

The images found were done using Flickr's api to make sure that any image found contained a gps address. Therefore, any suitable/similar images found would have a location that could be compared against the estimated location, provided by the user.

(This is a broken down, simple version of the process, without going too deep into how the algorithm works.) Any images found are then put through a comparison process in OpenCV.

Naturally, the IM2GPS research paper was of great use to me for this.

api - Finding an image on a map without EXIF Data - Stack Overflow

api image-processing comparison gis exif