**General notes:**
- Set MEDIA_URL (or whatever you use for uploaded content to point to S3 (ie. MEDIA_URL = "http://s3.amazonaws.com/MyBucket/"))
- Put django-storage in project_root/libraries, or change the paths to make you happy.
- This uses the functionality of django-storage, but *not* as DEFAULT_FILE_STORAGE.
The functionality works like so:
**Getting stuff to S3**
- On file upload of a noted model, a copy of the uploaded file is saved to S3.
- On any thumbnail generation, a copy is also saved to S3.
**On a page load:**
1. We check to see if the thumbnail exists locally. If so, we assume it's been sent to S3 and move on.
2. If it's missing, we check to see if S3 has a copy. If so, we download it and move on.
3. If the thumb is missing, we check to see if the source image exists. If so, we make a new thumb (which uploads itself to S3), and move on.
4. If the source is also missing, we see if it's on S3, and if so, get it, thumb it, and push the thumb back up, and move on.
5. If all of that fails, somebody deleted the image, or things have gone fubar'd.
**Advantages:**
- Thumbs are checked locally, so everything after the initial creation is very fast.
- You can clear out local files to save disk space on the server (one assumes you needed S3 for a reason), and trust that only the thumbs should ever be downloaded.
- If you want to be really clever, you can delete the original source files, and zero-byte the thumbs. This means very little space cost, and everything still works.
- If you're not actually low on disk space, Sorl Thumbnail keeps working just like it did, except your content is served by S3.
**Problems:**
- My python-fu is not as strong as those who wrote Sorl Thumbnail. I did tweak their code. Something may be wonky. YMMV.
- The relative_source property is a hack, and if the first 7 characters of the filename are repeated somewhere, step 4 above will fail.
- Upload is slow, and the first thumbnailing is slow, because we wait for the transfers to S3 to complete. This isn't django-storage, so things do genuinely take longer.
This is a simple way to embed images in emails, rather than use absolute links, which many clients will not show by default. It has not undergone extensive testing but it should get you started. Comments / suggestions welcome.
A template filter which wraps imagemagick's `convert` command. The filter acts upon a source image path, and returns the filtered image path.
usage: {{ source_path|convert:"-resize 64x64\!" }}
The filter parameter is the processing arguments for an ImageMagick 'convert' command. See e.g. http://www.imagemagick.org/Usage/resize/
Every image created is saved in a cache folder. This code does not handle removing obsolete cached images. If the filtered image path exists already, no image processing is carried out, and the path is returned.
Example mixin for creating and removing thumbnails on a model. Also adds some methods for accessing an url for an image size. It might be a better idea to use a custom image field instead of this approach.
Idea for getting the image url for different sizes from http://code.google.com/p/django-photologue
Example usage
<pre>
>>> p.get_small_image_url()
u'http://127.0.0.1:8000/site_media/photos/small_someimage.jpg'
</pre>
This custom processor is meant for use with sorl-thumbnail to add letterboxing functionality.
Add to your THUMBNAIL_PROCESSORS like so:
`THUMBNAIL_PROCESSORS = (
'sorl.thumbnail.processors.colorspace',
'sorl.thumbnail.processors.autocrop',
'sorl.thumbnail.processors.scale_and_crop',
'sorl.thumbnail.processors.filters',
# custom processors
'utils.processors.ltbx',
)
`
and then use in your templates like so:
`
{% thumbnail model.img_field 200x150 ltbx as thumb %}
<img src="{{ thumb }}" width="{{ thumb.width }}" height="{{ thumb.height }}" />`
Enjoy.
PIL IcoImagePlugin is twelve year old and it can't handle recent Windows ICO files. Here is a function that handles all ICO versions and preserve transparency.
Usage:
# Load biggest icon from file
image = load_icon('icon.ico')
# Save third icon as PNG
load_icon('icon.ico', 2).save('icon.png')
** Image on demand view **
I often post photos on photography fora. Most fora want you to place a link to a photo somewhere on the net, but different fora have different rules. Some fora want you to stick to a maximum of 800 pixels wide, some 700 pixel and some even strange values like 639 pixels. My own site uses 600 pixels so I end up resizing images all the time. Since I keep my originals with my gallery as well (hidden for public viewing) resizing on the fly would be a nice asset.
I'm using my previous snippet to apply a slight unsharp mask for better web display of my photos.
** usage **
This snippet takes the url to my photo application which is a simple link using the pk of my photo table and adds 'width'.jpg to the end (some fora check if the link is an image based on extenstion)
The view takes the width requested and creates the resized image from the original full size image or takes it from the cache for display on demand. To prevent a dozen directories I use a setting to specify which widths are allowed, providing room for several versions of the same image.
Any improvements are appreciated since I'm still rather inexperienced in Python and Django.
**A Magick PIL**
I used to do my image conversions with ImageMagick and system calls back in my PHP days. With Django PIL is the obvious choice for most image stuff, but frustrated by the lack of a proper unsharp mask function for PIL I found some code in the bits and pieces of documentation for PythonMagick. (yes I know, Kevin Cabazon wrote PIL_usm, but I could not get it to work, probably due to my inexperience. Anyway, this code makes it easy to convert back and forth from PIL to PythonMagick (maybe not such a good idea on a memory tight high loaded production server, but no problem on my private server (Pentium-M @ 1.8 Ghz with 1 GB Mem.)
**usage:**
usm takes a PIL image object. Radius and sigma is in pixels, amount 1 compares to 100% in photoshop, threshold 0.004 ~ (1/256) compares to 1 in photoshop: I'm using r=1,s=0.5,a=0.8,t=0.016 for roughly 800x600 images created from 3000x2000 (6MP) images. Experiment for your own preferences.
Easy way to generate image thumbnails for your models. Works with any Storage Backend.
From: [http://code.google.com/p/django-thumbs/](http://code.google.com/p/django-thumbs/)
**Usage example:**
==============
photo = ImageWithThumbsField(upload_to='images', sizes=((125,125),(300,200),)
To retrieve image URL, exactly the same way as with ImageField:
my_object.photo.url
To retrieve thumbnails URL's just add the size to it:
my_object.photo.url_125x125
my_object.photo.url_300x200
Note: The 'sizes' attribute is not required. If you don't provide it,
ImageWithThumbsField will act as a normal ImageField
**How it works:**
=============
For each size in the 'sizes' atribute of the field it generates a
thumbnail with that size and stores it following this format:
available_filename.[width]x[height].extension
Where 'available_filename' is the available filename returned by the storage
backend for saving the original file.
Following the usage example above: For storing a file called "photo.jpg" it saves:
photo.jpg (original file)
photo.125x125.jpg (first thumbnail)
photo.300x200.jpg (second thumbnail)
With the default storage backend if photo.jpg already exists it will use these filenames:
photo_.jpg
photo_.125x125.jpg
photo_.300x200.jpg
**Note:** It assumes that if filename "any_filename.jpg" is available
filenames with this format "any_filename.[widht]x[height].jpg" will be available, too.
Something I end up doing all the time, making a boolean variable show up as a nice image. With this code you can do the following:
`{% boolean_img user.is_active %}`
And get the following output:
`<img src="/media/icons/accept.png" alt="True" />`
All you need to do is use the custom templatetag code, load it in your template and use the `boolean_img` tag.
**Adjust templates, html and images where needed**
Couldn't get the original to work, and wanted more functionality (scale on x or y coordinates)
<img src="{{ object.image.url }}" alt="original image">
<img src="{{ object.image|thumbnail:"250w" }}" alt="image resized to 250w x (calculated/scaled)h ">
<img src="{{ object.image|thumbnail:"250h" }}" alt="image resized to (calculated/scaled)w x 250h h ">
<img src="{{ object.image|thumbnail:"250x200" }}" alt="image resized to 250wx200h ">
<img src="{{ object.image|thumbnail }}" alt="image resized to default 200w (or whatever you default it to) format">
Original http://www.djangosnippets.org/snippets/192/
Adapted http://www.djangosnippets.org/snippets/955/
Sampled From:
http://batiste.dosimple.ch/blog/2007-05-13-1/
http://vaig.be/2008/05/17/stdimagefield-improved-image-field-for-django/
This is the complete image_processor.py module, allowing you to add an image containing an arbitrary piece of text. I use this to label the horizontal axis of a skills-matrix report.
Credit www.renewtek.com for paying me to do this stuff!
Directive for inserting images using photolouge in django.
Usage:
Just make a .py with this code and import it in some apps models.py
Or make a custom formatter with django-template-utils.
A simple template filter that detects [iPernity](http://www.ipernity.com) static URLs and creates clickable thumbnail for them. Use it with [Lightbox](http://www.huddletogether.com/projects/lightbox2/) or any other funky image overlay script.
Your HTML code may contain this:
<p>A short example <img
src="http://...ipernity..."
title="The Description" />.</p>
After applying this filter it will become:
<p>A short example <a
href="http://...large version..."
title="The Title"><img
alt="The Title"
src="http://...thumb version..."/>
</a>.</p>
Thats all! You may have a look at this: [iPernity and static URLs](http://www.ipernity.com/group/api-users/discuss/20098)
**So you can upload rectangular pictures but still have square thumbnails.**
"Scale to **fill**" instead of the out of the box "scale to **fit**" you get with `Image.thumbnail`