#!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2006 Tarek Ziadé
#
# Authors:
#   Tarek Ziadé <tarek@ziade.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
# $Id: thumbnail.py 1655 2007-07-23 13:11:18Z rage $
"""Provide utilities to work with images"""
from PIL import Image
from StringIO import StringIO

def _new_size(image, width, height, scale):
    """calculate new size"""
    if width == -1:
        width = None
    if height == -1:
        height = None  
    img_width, img_height = image.size
    if width is None and height is None and scale is None:
        return image.size

    if width is not None and height is not None:
        return width, height

    if width is not None or height is not None:
        if width is not None:
            ratio = float(img_width) / float(width)
            height = float(img_height) / ratio
        else:
            ratio = float(img_height) / float(height)
            width = float(img_width) / ratio
    elif scale is not None:
        height = img_height * scale
        width = img_width * scale

    return int(width), int(height)

def generate(filename, width=None, height=None, scale=None):
    """returns a thumbnail"""
    image = Image.open(filename)
    width, height = _new_size(image, width, height, scale)

    #image.thumbnail((width, height), Image.ANTIALIAS)
    #image.resize((width, height), Image.ANTIALIAS)
    image.load()
    image = image._new(image.im.stretch((width, height), Image.NEAREST))

    data = StringIO()
    image.save(data, "JPEG")
    return data.getvalue()

def image_size(file):
    """returns image size"""
    return Image.open(file).size


