Skip to content

Instantly share code, notes, and snippets.

@pgcd
Created March 9, 2017 21:12
Show Gist options
  • Save pgcd/57f6b2c4dd0502279aa1a827f45d01ba to your computer and use it in GitHub Desktop.
Save pgcd/57f6b2c4dd0502279aa1a827f45d01ba to your computer and use it in GitHub Desktop.
Use Imagemagick to convert an uploaded image's color profile in Django
# It took me a day to figure out a way of converting the color profile before sending an uploaded image off to S3;
# The following works both for in-memory and temp file uploads (MemoryFileUploadHandler and TemporaryFileUploadHandler)
import subprocess
import logging
logger = logging.getLogger('imageprocessing')
color_profile = settings.BASE_DIR + 'sRGB.icc' # It should be an absolute path pointing to the icc file
f = uploadedfile # eg. the one you get from request.FILES.getlist(field_name)
command = ['convert', '-profile', color_profile, '-', '-']
try:
proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
content, err = proc.communicate(f.file.read())
except subprocess.CalledProcessError as e:
logger.error("Unable to convert image %s: error was %s" % (f, e))
except Exception as e:
logger.error("Unexpected exception processing image %s (%s): error was %s" % (f, e))
else:
f.file.seek(0)
f.file.truncate()
f.file.write(content)
# And now you can use f as normal, eg:
# Photo.objects.create(image=f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment