#-*- coding: cp936 -*-

import math
from PIL import Image

def swirl(image, degree = 50):
    '''
    @Ð§¹û£ºäöÎÐ£¬¶ÔÍ¼Ïñ½øÐÐäöÎÐÌØÐ§´¦Àí
    @param image: instance of Image
    @param degree: ±íÊ¾äöÎÐµÄ´óÐ¡[0, 100] 
    @return: instance of Image
    '''
    degree = min(max(0, degree), 100) / 1000.0
    
    if image.mode != "RGBA":
        image = image.convert("RGBA")
        
    width, height = image.size
    pix = image.load()
    
    center = width / 2, height / 2 # äöÎÐÖÐÐÄµã¾ÍÔÚÍ¼Æ¬ÖÐÐÄ
    
    dst_image = Image.new("RGBA", (width, height))
    dst_pix = dst_image.load()
    
    for w in xrange(width):
        for h in xrange(height):
            offset_x = w - center[0]
            offset_y = h - center[1]
            
            radian = math.atan2(offset_y, offset_x) # ½Ç¶È£¬Ê¹ÓÃmath.atan2(y, x)½øÐÐ¼ÆËã
            radius = math.sqrt(offset_x ** 2 + offset_y ** 2) # °ë¾¶£¬¼´ÏñËØµã¾àÖÐÐÄ¾àÀë
            
            # ¾àÀëÔ½Ô¶£¬Ðý×ªµÄ½Ç¶È¾ÍÔ½´ó
            # ÐÂ½Ç¶ÈÎª£º½Ç¶È + ¾àÀë ¡Á È¨ÖØ
            x = int(radius * math.cos(radian + radius * degree)) + center[0] 
            y = int(radius * math.sin(radian + radius * degree)) + center[1]
            
            x = min(max(0, x), width - 1)
            y = min(max(0, y), height - 1)
            
            dst_pix[w, h] = pix[x, y]
            
    return dst_image