2

I'm working on a simple message board app in Django that lets people upload images to be displayed in their posts. Since the div containing the posts is only 700px, I want to resize the uploaded images to a max width of something like 680px to save space rather than using css to display an image that's too large within the space constraints.

I've been searching this site, google and the PIL docs for a while and haven't found any way of resizing an image on one dimension while maintaining the original aspect ratio. Given my inexperience, it's possible that I'm just not recognizing a solution that's plain to someone who knows what to look for.

AndrewE
  • 353
  • 1
  • 4
  • 16
  • possible duplicate of [How do I resize an image using PIL and maintain its aspect ratio?](http://stackoverflow.com/questions/273946/how-do-i-resize-an-image-using-pil-and-maintain-its-aspect-ratio) – mechanical_meat Mar 18 '12 at 17:13

2 Answers2

3

As an another option, you might like to resize the images using CSS. Thus the images may retain their original resolution (enabling user to save them) and at the same time also fit into divisions nicely.

To prevent oversized images using CSS, you may use:

img {
max-width:100%;
height:auto;
}

Edit: Sorry Andrew, I don't know about PIL. However, if you know how to resize, and just need to work on maintaining ratio thing, then you can try something like:

def scale_dimensions(width, height, max_width):
    if width > max_width:
        ratio = max_width*1./width
        return (int(width*ratio), int(height*ratio))
    return (width, height)
Pratyush
  • 5,108
  • 6
  • 41
  • 63
  • Thanks Pratyush. That is my backup plan. However, in the context that this app will be used (office intranet), I think the space savings outweigh the ability to download copies of images that have already been degraded somewhat by the upload process and are themselves duplicates of images that can be found elsewhere on the LAN. – AndrewE Mar 18 '12 at 17:27
  • No worries. I think it is possible to skip the compression step in PIL. It just doesn't seem that useful in this situation. Thanks again for your help on this. – AndrewE Mar 18 '12 at 18:10
0
  • If what you want is to have the maximum dimension, either height or width, be a certain size, Image.thumbnail does precisely this.

  • If what you want is for the width to be a particular size, and the height to scale appropriately, you can use (not yet tested!):

    # my_image contains the input image; target_width contains the width to resize to.  
    (width, height) = my_image.size   
    target_height = int(height * (1.0 * target_width / width))   
    im.resize((target_width, target_height))  
    
MewX
  • 4,232
  • 1
  • 29
  • 38
Christophe
  • 2,052
  • 1
  • 19
  • 24