Example #1
0
def upload_image(request, topic_id):
    """Handles and validates uploaded image; both 100x100 and 25x25 image are saved"""
    from PIL import Image #@UnresolvedImport
    #For handling weired bug of PIL Linux package that only identifies BMP image;
    # See http://www.chipx86.com/blog/2008/07/25/django-tips-pil-imagefield-and-unit-tests/
    Image.init()
    
    image_form = ImageForm(request.POST, request.FILES)
    if image_form.is_valid():
        image = image_form.cleaned_data['image']
        image_size = image.size
        if image_size > 2048 * 1024: #size in bytes
            messages.error(request, '上传的图片请勿超过2M')
            return redirect("main.views.topic.topic", topic_id)
        
        dot_index = image.name.rfind('.')
        if dot_index == -1 or image.name[dot_index:] not in ['.png', '.gif', '.jpeg', '.jpg', '.PNG', '.GIF', '.JPEG', '.JPG']:
            messages.error(request, '上传的图片类型只能是png,gif或jpeg')
            return redirect("main.views.topic.topic", topic_id)
        
        image_extension = image.name[dot_index:]
        
        image.name = generate_random_file_name(32) + image_extension  #TODO:Need to query to prevent name collision
        #It's more secure to try: open than os.path.exists()
        #http://stackoverflow.com/questions/82831/how-do-i-check-if-a-file-exists-using-python
        while True:
            try:
                open(settings.MEDIA_ROOT + '/topic/' + image.name)
                image.name = generate_random_file_name(32) + image_extension
            except:
                break
          
        #make a 10x10 thumbnail
        import copy
        image_small = copy.copy(image)
        image_small.name = generate_random_file_name(32) + image_extension
        while True:
            try:
                open(settings.MEDIA_ROOT + '/topic/' + image_small.name)
                image_small.name = generate_random_file_name(32) + image_extension
            except:
                break 
        
        topic = Topic.objects.get(pk=topic_id)
        topic.image = image
        topic.image_small = image_small
        topic.save()
        return redirect("main.views.topic.topic", topic_id)
    else:
        messages.error(request, '你上传的文件不是图片')
        return redirect("main.views.topic.topic", topic_id)
Example #2
0
def gen_temp_file(image_url):
    #dot_index = image_url.rfind('.')
    #image_extension = image_url[dot_index:]
    image_extension = '.jpg'
    temp_name = generate_random_file_name(32)+image_extension
    temp_file_addr = settings.MEDIA_ROOT + 'apps/influence/' + temp_name
    temp_file = open(temp_file_addr, 'wb')
    temp_file.write(urllib2.urlopen(image_url).read())
    temp_file.close()
    return temp_file_addr
        
    
    
    
    
    
    
Example #3
0
 def daemon_add_item(self, url, title, snippet, published_time, channel_id):
     """
     return 0(int) if succeed; otherwise return error message
     Add channel_id if existing item doesn't have one; or append a channel_id if existing item has some
     Add channel_id for new item
     """
     try:
         url = url.strip()
         title = title.strip()
         snippet = snippet.strip()
         if not url or not title:
             return 'Error: url or title is null'
         
         maxlength = 5242880 #5 * 1024 * 1024bytes = 5MB
 #        redirect_return_value = process_redirect(url, maxlength)
 #        if 'url' in redirect_return_value:
 #            url = redirect_return_value['url']
 #        else:
 #            return redirect_return_value['error']
         
         url = url_normalize(url, charset='utf-8')
         parsed = urlparse.urlparse(url) #can be used to judge the source of item
         
         if url.find('www.') == -1:
             url_alias = 'http://' + 'www.' + url.replace('http://', '')
         else:
             url_alias = 'http://' + url.replace('http://www.', '')
         
         url_set = Item.objects.filter(url=url)
         url_alias_set = Item.objects.filter(url=url_alias)
         if len(url_set) > 0 or len(url_alias_set) > 0:
             if channel_id: #we need to update the channels for the existing news
                 if len(url_set) > 0:
                     item = url_set[0]
                 else:
                     item = url_alias_set[0]
                 if item.channels:
                     id_list = item.channels.split(',')
                     if not str(channel_id) in id_list:
                         id_list.append(str(channel_id))
                         item.channels = ','.join(id_list)
                         item.save()
                 else:
                     item.channels = str(channel_id)
                     item.save() 
                 
                     
             return 'Error: The item already exists.'
         
         headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                 #Accept-Language: en-us,en;q=0.5
                 #Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
                 'Keep-Alive': '115' ,
                 'Connection': 'keep-alive' ,
                 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.797.0 Safari/535.1'
                 }
         req = urllib2.Request(url, headers=headers)
         response = urllib2.urlopen(req, timeout=20)
         url = response.url
         url = url_normalize(url, charset='utf-8') #ensure url is normalized after redirect
         webpage = response.read(maxlength + 1)  
         if len(webpage) == maxlength + 1:
             return "Error: The webpage is more than max length"
         if response.info().get('Content-Encoding') == 'gzip':
             buf = StringIO(webpage)
             f = gzip.GzipFile(fileobj=buf)
             webpage = f.read()
         
         webpage_name = generate_random_file_name(32) + '.html'
         f = open(settings.MEDIA_ROOT + 'webpage/' + webpage_name, 'w+')
         f.write(webpage)  #Do not use unicode(soup) here, it will produce error on Linux server
         f.close()
         
         item = Item(name=title[:200], url=url[:255], snippet=snippet[:600], share_count=0, file='webpage/' + webpage_name)
         item.creator_id = None
         item.create_date = published_time
         if channel_id:
             item.channels = str(channel_id)
         item.save()
         return 0
     except:
         return 'Error in getting webpage'
Example #4
0
def influence_gen_image(str_inf_pk, friends_images):

    inf_pk = int(str_inf_pk)
    inf = Influence.objects.get(pk=inf_pk)
    
    im = Image.new("RGBA",(400,400),(255,255,255))
    bg = Image.open(settings.STATIC_ROOT + 'images/apps/influence-bg.jpg')
    im.paste(bg, (0,0,400,400))
    
    draw = ImageDraw.Draw(im)
    
    #Draw the score
    score_font = ImageFont.truetype(MSYHBD,35)
    score_xy = (300,55) if inf.influence_score > 9 else (312,55)
    draw.text(score_xy, unicode(inf.influence_score), font=score_font, fill=(255,255,255))
    
    #Paste the profile images
    profile_image_addr = gen_temp_file(inf.profile_image_url)
    profile_image = Image.open(profile_image_addr)
    profile_image = profile_image.resize((57,57), Image.ANTIALIAS)     
    im.paste(profile_image, (90,160,147,217))
    #im.paste(profile_image, (92,170,142,220)) #Original size
    os.remove(profile_image_addr)
    
    #Paste images for influenced friends
    friends_xy = [89,252]
    forloop = 0
    tip_font = ImageFont.truetype(MSYH,13)
    if len(friends_images) == 0:
       draw.text((145,262), u'暂时没有好友受我影响:(', font=tip_font, fill=(0,0,0))
    else: 
        for image in friends_images:
            friend_image_addr = gen_temp_file(image)
            friend_image = Image.open(friend_image_addr)
            friend_image = friend_image.resize((31,31), Image.ANTIALIAS)     
            im.paste(friend_image, tuple(friends_xy))
            friends_xy[0] += 46
            os.remove(friend_image_addr)
            forloop += 1
        draw.text((friends_xy[0]+4,262), u'深受我影响:)', font=tip_font, fill=(0,0,0))    
    
    #Fill in the number of fans and active fans
    followers_str = prettify_count(inf.follower_count)
    active_followers_str = prettify_count(inf.active_follower_count)
    follower_font = ImageFont.truetype(MSYH,14)
    draw.text((17,271), followers_str, font=follower_font, fill=(255,255,255))
    draw.text((47,245), active_followers_str, font=follower_font, fill=(255,255,255))
    
    #Fill in the name of user
    name_font = ImageFont.truetype(MSYH,16)
    draw.text((160,160), unicode(inf.screen_name), font=name_font, fill=(0,0,0))
    
    #Fill in status_count and influenced people
    status_font = ImageFont.truetype(MSYH,12)
    draw.text((300,173), unicode(inf.status_count), font=status_font, fill=(255,128,0))
    influence_str = prettify_count(inf.influence_count)
    draw.text((300,200), influence_str, font=status_font, fill=(255,122,50))
    #Fill in the 'energy bar' for status count and influenced people
    bar = Image.open(settings.STATIC_ROOT + 'images/apps/green-bar.gif')
    status_bar_score = int(math.ceil(math.sqrt(inf.status_count*1.0/3000)*100))
    influence_bar_score = inf.influence_score
    for i in range(status_bar_score):
        im.paste(bar,(229+i,188))
    for i in range(influence_bar_score):
        im.paste(bar,(229+i,215))

    del draw
    image_name = 'apps/influence/' + generate_random_file_name() + '.jpg'
    print image_name
    inf.result_image = image_name
    inf.save()
    im.save(settings.MEDIA_ROOT + image_name, "JPEG")