Max Picture Width with Django

October 4, 2010

Following a recent site redesign, we found that our latest photos were slightly too wide. We thought they were all capped at 800px wide, but in fact what we'd done is to resize them to 600px high, and given our new Nikon D5000 produced pictures that were slightly wider than our previous Panasonic, the generated images were 903x600px.

We needed a way to fix this that didn't mean resizing lots of pictures on the server (though that would undoubtedly be the most performant method going forwards!). The different in size wasn't large, and the resizing was difficult, we opted to let Django generate width and height fields onto the img tag, but only where the image would otherwise be too large. Portrait images were to be left alone.

views.py

Here's the view code that specifies a Width and Height variable to the template if the size is greater than 800 wide:

lWidth = None
lHeight = None

if lImage.image.width > 800:
    lWidth = 800
    lFactor = lImage.image.width / 800.0
    lHeight = lImage.image.height / lFactor

template.html

In the template, we used the Width and Height value, but only if it was specified:

{% if Height %}
<img src="{{Image.image.url}}" alt="{{ Image.name }}" width="{{Width}}" height="{{Height}}"/><br/>
{% else %}
<img src="{{Image.image.url}}" alt="{{ Image.name }}"/><br/>
{% endif %}

Script

For those interested, here's the script we use which looks through a directory for jpg files and writes smaller ones to an images directory. It relies on ImageMagick

#!/bin/sh
#Script to resize jpeg images to 800x600 ish

upperlist=`ls *.JPG`
mkdir images
for i in $upperlist
do
  file=${i##*/}
  base=${file%%.*}
  echo $base.jpg
  mv $base.JPG $base.jpg
done

list=`ls *.jpg`
for i in $list
do
  file=${i##*/}
  base=${file%%.*}
  echo $base.jpg
  convert -geometry x600 $base.jpg images/$base.jpg
done