CR2 to JPG: Python script

June 01, 2017

CR2 to JPG: Python script

Photo above of Milford Sound from our 2013 to New Zealand.

A friend of mine had recently sold me on the idea of moving all my photos to Google Photos. I had everything backed up on a home server and on various drives all over the place and it was time to put them all in one easy to use and easy to share centralised 3rd party service.

Whilst going through this process I found that a lot of the photos I wanted to move across needed to be organised or categorised in some way, and one issue I kept encountering when converting CR2 format files was that timestamps were getting lost.

On top of this, CR2 files are huge, and I needed it to cut the time of uploading 1,000+ raw CR2 photos to Google Photos.

As a result, I wrote script allows you to convert CR2 format photos to JPG and retains the original timestamp of the CR2 file.

There are many other ways to do this, including Photoshop actions if you're after a visual/gui based approach. There are also bash scripts that can achieve similar results, but I wanted to tinker and play with Python.

Instructions

It's very easy to setup, just follow these steps:

Step 1: Clone or download from https://github.com/mateusz-michalik/cr2-to-jpg

Step 2: Install required packages with pip install

Step 3: Set permissions to execute chmod +x cr2-to-jpg.py

Step 4: Run the script and pass source and destination folders, for example: ./cr2-to-jpg.py --source ~/Desktop/raw --destination ~/Desktop/converted

How it works

The gist of it is that I first get the original file timestamp:

file_timestamp = os.path.getmtime(raw_image)

I then convert the CR2 to JPG

# parse CR2 image
raw_image_process = raw.Raw(raw_image)
buffered_image = numpy.array(raw_image_process.to_buffer())

# check orientation due to PIL image stretch issue
if raw_image_process.metadata.orientation == 0:
    jpg_image_height = raw_image_process.metadata.height
    jpg_image_width = raw_image_process.metadata.width
else:
    jpg_image_height = raw_image_process.metadata.width
    jpg_image_width = raw_image_process.metadata.height

# prep JPG details
jpg_image_location = converted_dir + file_without_ext + '.jpg'
jpg_image = Image.frombytes('RGB', (jpg_image_width, jpg_image_height), buffered_image)
jpg_image.save(jpg_image_location, format="jpeg")

And finally write the original timestamp to the JPG file with one line of code:

os.utime(jpg_image_location, (file_timestamp,file_timestamp))

You can see the full source code here: https://github.com/mateusz-michalik/cr2-to-jpg/blob/master/cr2-to-jpg.py