def resize_to(file, w, h):

  """ 
  rezizes an image to given dimensions
  cropping it in order to keep proportions
  """
  width, height = getImageInfo(file)
  #ratio = width/height
  #ratio_n = w/h
  #ratio_new = ratio/ratio_n
  w_new = height * (w/h)
  h_new = width / (w/h)
  #cut width
  if w_new < width:
    
    cropoff =  (abs(width  -  w_new)*.5)/width
    file =  images.crop(file,top_y=0.0, bottom_y=1.0,left_x=cropoff,right_x=1.0  - cropoff)
    file = images.resize(file, height= h)
  #cut height
  elif h_new < height:
    
    #print h_new
    cropoff =  (abs(height  -  h_new)*.5)/height
    file =  images.crop(file,top_y=cropoff, bottom_y=1.0 - cropoff,left_x=0.0,right_x=1.0 )
    file = images.resize(file, width= w)
  else:
    file = images.resize(file, width = w, height= h)
    
  file = images.im_feeling_lucky(file, images.JPEG)
  return file
Esempio n. 2
0
    def post(self):
        imgLocation = self.request.get('imgLocation')
        if imgLocation != "":
            streamKey = ndb.Key(urlsafe=self.request.get('streamKey'))
            img = Image()
            img.stream = streamKey
            img_temp = self.request.get('img')
            img.Thumbnail = images.resize(img_temp ,width=300, height=300, crop_to_fit = True)
            img.full_size_image = img_temp
            img.geoPt = ndb.GeoPt(imgLocation)
            img.put()
            print "IMG.TIME = "
            print img.time
            stream = streamKey.get()
            stream.lastTimeUpload = img.time
            stream.put()

            self.redirect('/View_single?streamKey='+streamKey.urlsafe())
        else:
            # user chose not to share his geo location
            streamKey = ndb.Key(urlsafe=self.request.get('streamKey'))
            img = Image()
            img.stream = streamKey
            img_temp = self.request.get('img')
            img.Thumbnail = images.resize(img_temp ,width=300, height=300, crop_to_fit = True)
            img.full_size_image = img_temp
            img.put()
            print "IMG.TIME = "
            print img.time
            stream = streamKey.get()
            stream.lastTimeUpload = img.time
            stream.put()

            self.redirect('/View_single?streamKey='+streamKey.urlsafe())
Esempio n. 3
0
    def post(self):
        if users.is_current_user_admin():

            for file_data in self.request.POST.getall('photo_file'):
                  #print "File Contents : ", file_data.value
                user = users.get_current_user()
                date_time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
                data_id = date_time + '_' + str(randint(0,1000))

                item = Photo_db(id=data_id)
                item.data_id = data_id
       
                item.user_id = users.get_current_user()
                item.year = self.request.get('year')
                item.event_type = self.request.get('event_type')
                item.catagory = item.year + '_' + item.event_type
                # print 'lala:', item.catagory
      # -
                photo_file = file_data.value
                if photo_file:
                    photo = images.Image(image_data=photo_file)
                    if photo.width > photo.height:
                        item.image_data = db.Blob(images.resize(photo_file, 800))
                        item.flag = 'horizontal'
                    else:
                        item.image_data = db.Blob(images.resize(photo_file, 600))
                        item.flag = 'vertical'
           #
                item.put()
                time.sleep(1)
                self.redirect('/manage/photo_data')
Esempio n. 4
0
    def post(self):
        filename = self.request.POST['img'].filename.split('.')[0]
        name = slugify(filename[:32])
        logging.info("name: %s", name)
        media = models.MediaModel.get_or_insert(name)
        image_data = self.request.get('img')

        image_object = images.Image(image_data)       # convert image to GAE image object for manipulation
        image_object._update_dimensions()             # make ._height and ._width accurate (not None)

        # scale image for different sizes, don't ever blow it up, large size not always produced
        if image_object._width > 960 or image_object._height > 960:
            large = images.resize(image_data, IMAGE_SIZE_LARGE, IMAGE_SIZE_LARGE, images.JPEG)
            media.large = large
        else:
            media.large = None

        if image_object._width > 480 or image_object._height > 480:
            mobile = images.resize(image_data, IMAGE_SIZE_MOBILE, IMAGE_SIZE_MOBILE, images.JPEG)
            media.mobile = mobile
        else:
            media.mobile = image_data

        thumbnail = images.resize(image_data, IMAGE_SIZE_THUMBNAIL, IMAGE_SIZE_THUMBNAIL, images.JPEG)
        media.thumbnail = thumbnail

        media.put()
        self.redirect('/admin#media')
Esempio n. 5
0
        def post(self, **kwargs):
            image = self.request.files.get('image_upload').read()
            datestring = self.request.form.get('start-date')
            start_date = self.castTime(datestring)
            #end_date = self.castTime(self.request.form.get('finish-date'), self.request.form.get('finish-time'))
            #start_date = datetime.datetime(self.request.form.get('start_time'))
            
            params = {
                        "file": images.resize(image, 90, 90),
                        "file150": images.resize(image, 150, 150),
                        "filetype": self.request.files.get('image_upload').filename,
                        "name" : self.request.form.get('name'),
                        "start_date" : start_date,
#                        "end_date" : end_date,
                        "description" : self.request.form.get('description'),
                        "creator" : self.auth.user,
                        "people_invited" : self.request.form.getlist('contacts[]'),
#                        "type" : self.request.form.get('type'),
                        "setlist" : self.request.form.getlist('songs[]')
                    
                  }
            manager = EventDelegate('Event')
            value = manager.add(params)
            songs = Song.all()
            
            return self.redirect('/dashboard')
Esempio n. 6
0
def editImage(form):
  postID = form.getfirst("postID", "none")
  if postID == "none":
    thePost = algaeModels.algaeImage()
  else:
    thePost = algaeModels.algaeImage.get(postID)
  theTitle = form.getfirst("postTitle", "Untitled").decode( 'utf-8', 'ignore')
  thePost.postTitle = theTitle
  url = re.sub(r' ', "_", theTitle)
  url = re.sub(r'\W', "", url)
  url = re.sub(r'_+', "-", url)
  if url != thePost.cleanURL:
    url = algaePython.noDupeURL(url, 'algaeImage')
  thePost.cleanURL = url
  theImage = form.getfirst("img", "")
  thePost.imgData = db.Blob(theImage)
  smImage = images.resize(theImage, algaeUserConfig.smallImageSize, algaeUserConfig.smallImageSize)
  thePost.smData = db.Blob(smImage)
  mdImage = images.resize(theImage, algaeUserConfig.mediumImageSize, algaeUserConfig.mediumImageSize)
  thePost.mdData = db.Blob(mdImage)
  lgImage = images.resize(theImage, algaeUserConfig.largeImageSize, algaeUserConfig.largeImageSize)
  thePost.lgData = db.Blob(lgImage)
  thePost.mimeType = form['img'].type
  thePost.fileName = form['img'].filename
  if form.getfirst("isPublished", "False") == "on":
    thePost.isPublished = True
  else:
    thePost.isPublished = False
  thePost.put()
  print "Location: admin?saved=yes&edit=image&key=" + str(thePost.key())
  print 'Content-Type: text/html\n'
    def post(self):
        user = users.get_current_user()
        if self.request.get("key"):
            logging.info("URL safe = " + self.request.get("key"))
            pupil_key = ndb.Key(urlsafe=self.request.get("key"))
            logging.info("Sring rep of REAL key" + str(pupil_key))
            pupil = pupil_key.get()
            pupil.name = self.request.get("pupilName")
            pupil.class_name = self.request.get("className")
            pupil.level = self.request.get("level")
            if self.request.get("avatar"):
                logging.info("self.request.get(avatar " + self.request.get("avatar"))
                avatar_image = images.resize(self.request.get("avatar"), 256, 256)
                pupil.avatar = None
                pupil.avatar = avatar_image
            else:
                avatar_image = None
            pupil.put()
        else:
            logging.info("URL safe = " + self.request.get("key"))
            if self.request.get("avatar"):
                avatar_image = images.resize(self.request.get("avatar"), 256, 256)
            else:
                avatar_image = None

            new_pupil = Pupil(parent=get_parent_key(user),
                              name = self.request.get("pupilName"),
                              class_name = self.request.get("className"),
                              level = self.request.get("level"),
                              avatar = avatar_image)
            new_pupil.put()
        self.redirect(self.request.referer)
Esempio n. 8
0
  def post(self):
    player = Player.get(self.request.get("player_key"))
    if player.pic:
      player.pic.delete()
      player.pic = None
      player.put()

    player_pic = self.request.get("pic")
    box    = db.Blob(images.resize(player_pic, 380, 532))
    leader = db.Blob(images.resize(player_pic, 80, 112))
    thumb  = db.Blob(images.resize(player_pic, 20, 28))

    pic = PlayerPicture(key_name=player.key().name(),
        box=box, leader=leader, thumb=thumb)
    pic.put()

    player.pic = pic
    player.put()

    views.PlayerBox.clear(player.key())
    views.PlayerLeaders.clear()

    # I need to give a response or I get an error. Nobody on the internet seems
    # to know why.  See https://github.com/malsup/form/issues#issue/22.
    self.response.out.write("OK") 
Esempio n. 9
0
  def refresh_employer_images(self, employer_list=False):
        #TODO: Reduce multiple writes
		from google.appengine.api import images
		save_profiles = []
		from model.user import Profile, ProfilePicture
		if not employer_list: employers = Employer.all().fetch(1000)
		else: employers = employer_list
		logging.info('saving employer images for %s', employers)
		for e in employers:
			p_path = ROOT_PATH + "/data/img/business/"
			try: image_file = open(p_path + str(e.unique_identifier) + ".png")
			except: continue
			image = image_file.read()
			small_image = images.resize(image, 45, 45)
			large_image = images.resize(image, 95, 95)
			new_image = ProfilePicture(small_image = small_image,
									 large_image = large_image,
									 type = "employer"
									 )
			new_image.put()
			logging.info('saved employer image for %s', e.unique_identifier)
			this_profile = Profile.get_by_key_name(e.unique_identifier)
			try:this_profile.photo = new_image
			except:
				logging.info('unable to refresh employer image for %s', e.unique_identifier)
				continue
			save_profiles.append(this_profile)
		logging.info('refreshed %d employer images', len(save_profiles))
		if save_profiles: print "refreshed employer images for", [p.unique_identifier for p in save_profiles]
		db.put(save_profiles)
Esempio n. 10
0
 def post(self):
     pen = updateable_pen(self)
     if not pen:
         return
     updobj = pen  # default is uploading a pic for your profile
     picfor = self.request.get('picfor') or "pen"
     if picfor == "coop":
         ctm, role = coop.fetch_coop_and_role(self, pen)
         if not ctm:
             return  # error already reported
         if not role or role != "Founder":
             return srverr(self, 403, "Only founders may upload a coop pic")
         updobj = ctm
     upfile = self.request.get("picfilein")
     if not upfile:
         return srverr(self, 400, "No picture file received")
     logging.info("Pic upload for " + picfor + " " + str(updobj.key().id()))
     try:
         # resize images to max 160 x 160 px
         if picfor == "coop":
             ctm.picture = db.Blob(upfile)
             ctm.picture = images.resize(ctm.picture, 160, 160)
             ctm.modified = nowISO()
             cached_put(ctm)
         else:
             pen.profpic = db.Blob(upfile)
             pen.profpic = images.resize(pen.profpic, 160, 160)
             pen.modified = nowISO()
             cached_put(pen)
     except Exception as e:
         return srverr(self, 500, "Profile picture upload failed: " + str(e))
     self.response.headers['Content-Type'] = 'text/html'
     self.response.out.write("Done: " + pen.modified)
Esempio n. 11
0
 def post(self):
     """ 上傳圖片 """
     img = DBImage()
     img.thumbnail = images.resize(self.request.get("Filedata"), 125, 125)
     img.original = images.resize(self.request.get("Filedata"),800,800)
     img.put()
     self.info = str(img.key())
Esempio n. 12
0
 def post(self):
     if users.get_current_user():
         if self.request.get('avatar'):
             user = users.get_current_user()
             dbuser = UsersDB.gql("WHERE user = '******'" % user.nickname())
             usert = dbuser.get()
             avatar = images.resize(self.request.get("avatar"), 100, 100)
             avatar_mob = images.resize(self.request.get("avatar"), 50, 50)
             avatar_big = self.request.get("avatar")
             usert.avatar = db.Blob(avatar)
             usert.avatar_mob = db.Blob(avatar_mob)
             usert.avatar_big = db.Blob(avatar_big)
             usert.put()
             return True
         elif self.request.get('avatar_delete'):
             user = users.get_current_user()
             dbuser = UsersDB.gql("WHERE user = '******'" % user.nickname())
             usert = dbuser.get()
             usert.avatar = db.Blob(None)
             usert.avatar_mob = db.Blob(None)
             usert.avatar_big = db.Blob(None)
             usert.put()
             self.redirect("/mypage")
         else:
             self.redirect("/")
Esempio n. 13
0
    def post(self):
        errors = []
        
        post = Post()
        post.user = db.get(self.request.get('user'))

        description = self.request.get('description')
        if not description or len(description.strip()) == 0:
            errors.append('Informācija par velosipēdu ir obligāta')
        else:
            post.description = description

        date = self.request.get('date')
        try:
            post.stolen_on = datetime.datetime.strptime(date, '%Y-%m-%d').date()
        except:
            errors.append('Norādīts kļūdains datums')

        time = self.request.get('time')
        if time:
            try:
                post.stolen_at = datetime.datetime.strptime(time, '%H:%M').timetz()
            except:
                errors.append('Norādīts kļūdains laiks')
            
        photo = self.request.get("photo")
        if not photo:
            errors.append('Nav norādīta bilde')
        else:
            try:
                post.photo = db.Blob(images.resize(photo, 600))
                post.thumbnail = db.Blob(images.resize(photo, 250))
            except Exception, e:
                logging.error(e)
                errors.append('Kļūda apstrādājot bildi (maksimāli pieļaujamais bildes izmērs ir 1 Mb)')
Esempio n. 14
0
  def post(self):
    team = Team.get(self.request.get("team_key"))
    if team.custom_logo:
      team.custom_logo.delete()
      team.custom_logo = None
      team.put()

    team_logo = self.request.get("logo")
    box    = db.Blob(images.resize(team_logo, 128, 128))
    thumb  = db.Blob(images.resize(team_logo, 20, 20))

    logo = TeamLogo(key_name=team.key().name(), box=box, thumb=thumb)
    logo.put()

    team.custom_logo = logo
    team.put()

    views.RecentMatches.clear()
    views.TeamBox.clear(team.key())
    views.TeamLeaders.clear()

    for player in team.player_set:
      views.PlayerBox.clear(player.key())

    # I need to give a response or I get an error. Nobody on the internet seems
    # to know why.  See https://github.com/malsup/form/issues#issue/22.
    self.response.out.write("OK") 
	def post(self):
		post = common.ImagePost()
		image = self.request.get("img")
		thumbnail = images.resize(image,100)
		middlesize = images.resize(image,200)
		post_id = -1
		posts = db.GqlQuery("SELECT * FROM BlogPost ORDER BY post_id DESC LIMIT 1")
		for po in posts:
			post_id = po.post_id + 1
		image_id = findImageIdNumber(post_id)
		image = self.request.get("img")
		if(image):
			post.post_id = post_id
			post.image_id = image_id
			post.image = db.Blob(image)
			post.thumbnail = db.Blob(thumbnail)
			post.middlesize = db.Blob(middlesize)
			post.put()
			
			blogpost = common.BlogPost()
			blogpost.post_id = post_id
			
			titleFromPost = self.request.get("title")
			if(titleFromPost):
				blogpost.title = titleFromPost
			else:
				blogpost.title = "mobile picture"
			
			blogpost.content = "<br/><img src=\"/fullimage?img_id=%s\">" % post.key()
			if(str(self.request.get("published"))  == "Yes"  ):
				blogpost.published = True
			else:
				blogpost.published = False
			blogpost.put()
    def post(self):
        "Upload via a multitype POST message"

        img = self.request.get("img")
        # if we don't have image data we'll quit now
        if not img:
            self.redirect("/")
            return
        try:
            width = int(self.request.get("width"))
            hight = int(self.request.get("height"))
        except ValueError:
            image_content = img
        else:
            image_content = images.resize(img, width, height)

        original_content = img

        thumb_content = images.resize(img, 100, 100)

        image = Image()

        image.image = db.Blob(image_content)

        image.original = db.Blob(original_content)
        image.thumb = db.Blob(thumb_content)
        image.user = users.get_current_user()
        image.put()
        self.redirect("/")
Esempio n. 17
0
	def refresh_subject_images(self, this_proficiency=False):
		if not this_proficiency: 
		    proficiencies = Proficiency.all().fetch(1000)
		    self.delete_subject_images()
		    self.refresh_default_subject_image()
		else: 
		    proficiencies = [this_proficiency]
		    self.delete_subject_images(subject=this_proficiency)
		all_images = []
		for p in proficiencies:
			p_path = ROOT_PATH + "/data/img/subject/" + str(p.name) + "/"
			save_images = []
			for n in range(4):
				try: image_file = open(p_path + str(n) + ".png")
				except: continue
				image = image_file.read()
				small_image = images.resize(image, 120, 80)
				large_image = images.resize(image, 360, 240)
				new_image = SubjectImage(key_name = str(p.name + "_" + str(n)), #unique keyname
				                         small_image = small_image,
				                         large_image = large_image,
				                         proficiency = p
									     )
				save_images.append(p.new_image(image))
				all_images.append(new_image)
			db.put(save_images)
			logging.info('refreshed %d subject images', len(save_images))
		return len(all_images)
Esempio n. 18
0
	def post(self):
		
		action = self.request.get('action')
		id = int(self.request.get('id'))
		
		if action == "add":
			food = Contact()
			food.name = self.request.get('name')
			food.your_review = self.request.get('your_review')
			food.rating = self.request.get('rating')
			food.place_checkmark = self.request.get('place_checkmark')
			if self.request.get('photo') == "":
				food.photo = base64.b64encode("")
			else:
				food.photo = base64.b64encode(str(images.resize(self.request.get('photo'), 140, 140)))
			food.put()
			self.redirect('/view')
		elif action == "edit":
			food = Contact.get_by_id(id)
			food.name = self.request.get('name')
			food.your_review = self.request.get('your_review')
			food.rating = self.request.get('rating')
			food.place_checkmark = self.request.get('place_checkmark')
			if self.request.get('photo_choice') == "change":
				if self.request.get('photo') == "":
					food.photo = base64.b64encode("")
				else:
					food.photo = base64.b64encode(str(images.resize(self.request.get('photo'), 140, 140)))
			food.put()
			self.redirect('/view')
		elif action == "delete":
			food = Contact.get_by_id(id)
			food.key.delete()
			self.redirect('/view')
 def post(self):
     key = self.request.get("key")
     if key:
         cliente = ndb.Key(urlsafe=key).get()
         rutas = RutaHelper.query_all()
         rutaSupervisor = UsuarioHelper.query_all_rutas(self.user.key)
         self.render("new_client.html", rutas=rutas, cliente=cliente, rutaSupervisor=rutaSupervisor)
         return
     else:
         documento = int(self.request.get("documento")) if self.request.get("documento") else None
         nombres = self.request.get("nombres")
         apellidos = self.request.get("apellidos")
         dir_casa = self.request.get("dir_casa")
         tel_casa = int(self.request.get("tel_casa")) if self.request.get("tel_casa") else None
         celular = int(self.request.get("celular")) if self.request.get("celular") else None
         nombre_est = self.request.get("nombre_est")
         dir_est = self.request.get("dir_est")
         imagen_documento = self.request.get("imagen_documento")
         if imagen_documento:
             imagen_documento = images.resize(imagen_documento, 150, 112)
         else:
             imagen_documento = None
         imagen_negocio = self.request.get("imagen_negocio")
         if imagen_negocio:
             imagen_negocio = images.resize(imagen_negocio, 150, 112)
         else:
             imagen_negocio = None
         if self.user.role == "admin" or self.user.role == "supervisor":
             ruta = self.request.get("urlkey_ruta")
         else:
             if self.user.ruta:
                 ruta = self.user.ruta.urlsafe()
             else:
                 ruta = UsuarioHelper.query_all_rutas(self.user.key)[0].ruta.urlsafe()
         key = self.request.get("client_urlkey")
         if key:
             cliente = ndb.Key(urlsafe=key)
             alert = ClientHelper.actualizar_registro(cliente, documento, 
                                                      ruta, nombres,
                                                      apellidos, dir_casa,
                                                      tel_casa, celular,
                                                      nombre_est, dir_est, 
                                                      imagen_documento, imagen_negocio)
         else:
             alert = ClientHelper.nuevo_registro(documento, 
                                                 ruta, nombres,
                                                 apellidos, dir_casa,
                                                 tel_casa, celular,
                                                 nombre_est, dir_est, 
                                                 imagen_documento, imagen_negocio)
         if alert[0] == "alert-danger":
             rutas = RutaHelper.query_all()
             rutaSupervisor = UsuarioHelper.query_all_rutas(self.user.key)
             self.render("new_client.html", rutas=rutas, cliente=None, 
                 rutaSupervisor=rutaSupervisor, alert=alert)
         else:
             time.sleep(1)
             self.redirect("/cliente?urlkey_ruta=" + ruta)
Esempio n. 20
0
def watermark(image):
    img = images.Image(images.resize(str(image), 800, 600))
    with open(settings.WATERMARK_PATH, 'rb') as f:
        watermark = images.Image(images.resize(f.read(), img.width, img.height))
        x = (img.width - watermark.width)/2
        y = (img.height- watermark.height)/2 
        return images.composite([
            (img, 0, 0, 1.0, images.TOP_LEFT, ), 
            (watermark, x, y, 0.2, images.TOP_LEFT, ),
        ], img.width, img.height, 0, images.JPEG,)
Esempio n. 21
0
    def encode(self, raw_picture, name=False, ext=False):
        """
        Wraps the creation of resized pictures from uploaded data
        """
        self.encode_name(raw_picture, name, ext)

        self.mime_type = raw_picture.type
        self.source = db.Blob(raw_picture.value)

        self.thumb = images.resize(raw_picture.value, 120, 90)
        self.default = images.resize(raw_picture.value, 360)
Esempio n. 22
0
  def new_image(self, image): # for views=
	from google.appengine.api import images
	small_image = images.resize(image, 120, 80)
	large_image = images.resize(image, 360, 240)
	
	new_image = SubjectImage(
	                         small_image = small_image,
	                         large_image = large_image,
	                         proficiency = self
						     )
	return new_image # requires put() to save!
Esempio n. 23
0
 def post(self):
     upload_files = base64.b64decode(self.request.get("myPhoto").replace('data:image/png;base64,', ''))
     foto = Foto()
     foto.hint = 0
     foto.image = images.resize(upload_files, width=600, output_encoding=images.PNG)
     foto.title = self.request.get('message') or ""
     foto.shared = True
     foto.mobile = False
     try:
         foto.put()
     except Exception, e:
         foto.image = images.resize(upload_files, width=600, output_encoding=images.PNG)
Esempio n. 24
0
 def resizeImg(self,img,height,width):
     if(height is not "" and width is not ""):
         height = int(height)
         width = int(width)
         img.imageData = images.resize(image_data=img.imageData,width=width,height=height)
     elif(width is not ""):
         width = int(width)
         img.imageData = images.resize(image_data=img.imageData,width=width)
     elif(height is not ""):
         height = int(height)
         img.imageData = images.resize(image_data=img.imageData,height=height)
     return img
Esempio n. 25
0
File: rpc.py Progetto: jamslevy/PQ
 def post(self):
 	try:
 		small_image = images.resize(self.request.get("img"), 45, 45)
 		large_image = images.resize(self.request.get("img"), 95, 95)
 		new_image = ProfilePicture(small_image = small_image,
 		                           large_image = large_image)
 		new_image.put()
 		new_image.key_name = str(new_image.key())
 		new_image.put()
 		self.response.out.write(new_image.key_name)
 	except:
 		self.response.out.write('error') 
Esempio n. 26
0
	def refresh_default_subject_image(self):
		tile_path = ROOT_PATH + "/data/img/base/pq_tile.png"
		image_file = open(tile_path)
		image = image_file.read()
		small_image = images.resize(image, 120, 80)
		large_image = images.resize(image, 360, 240)
		from model.proficiency import DefaultSubjectImage
		for i in DefaultSubjectImage.all().fetch(1000): i.delete() # delete old images 
		default_image = DefaultSubjectImage(small_image = small_image,
									 large_image = large_image)
		default_image.put()
		logging.info('saved default image: %s', default_image)
		return "saved default image: ", default_image							     
 def post(self):
     "Upload via a multitype POST message"
     
     try:
         # check we have numerical width and height values
         width = int(self.request.get("width"))
         height = int(self.request.get("height"))
     except ValueError:
         # if we don't have valid width and height values
         # then just use the original image
         image_content = self.request.get("img")
     else:
         # if we have valid width and height values
         # then resize according to those values
         image_content = images.resize(self.request.get("img"), width, height)
     
     # get the image data from the form
     original_content = self.request.get("img")
     # always generate a thumbnail for use on the admin page
     thumb_content = images.resize(self.request.get("img"), 100, 100)
     
     # create the image object
     image = Image()
     # Try and create an s3 connection
     if len(awskeys.AWS_ACCESS_KEY_ID) > 0 and len(awskeys.AWS_SECRET_ACCESS_KEY) > 0:
         s3 = GoogleS3.AWSAuthConnection(awskeys.AWS_ACCESS_KEY_ID, awskeys.AWS_SECRET_ACCESS_KEY)
     else:
         s3 = None
     
     # and set the properties to the relevant values
     image.image = db.Blob(image_content)
     image.user = users.get_current_user()
     
     if s3 is None:
         # we always store the original here in case of errors
         # although it's currently not exposed via the frontend
         image.original = db.Blob(original_content)
         image.thumb = db.Blob(thumb_content)
         # store the image in the datasore
         image.put()
     else:
         # we want to store in S3, so store the data and use the key
         image.put()
         # Put the 3 different images
         s3.put(awskeys.BUCKET_NAME,str(image.key()) + "_original",original_content)
         s3.put(awskeys.BUCKET_NAME,str(image.key()) + "_thumb",thumb_content)
         s3.put(awskeys.BUCKET_NAME,str(image.key()) + "_image",image_content)
             
     
     # and redirect back to the admin page
     self.redirect('/')
Esempio n. 28
0
def makeplayer(name, money=100000, debt=0, percent=0.03, trust=1.0, 
               solid=False, growth=0.01, bot=False, user=None, 
               lastdividenddate=None, lastdividendamount=0.0, 
               points=0, occupation=None, levelname='', level=1,
               alerts=[], alertsarchive=[], about='', friends=[],
               totalinvestedamount=0.0, totalinvestorsamount=0.0,
               lastlogindate=datetime.datetime.now(),
               lastpaydate=datetime.datetime.now(), bgselection=5,
               locked=False, taxes=0.0, messages=[], messagearchive=[]):
    newplayer = models.Player()
    newplayer.playerid = str(uuid.uuid4())
    newplayer.name = str(name)
    newplayer.namenormal = str(name).upper()
    newplayer.money = float(money)
    newplayer.debt = float(debt)
    newplayer.percent = float(percent)
    newplayer.trust = float(trust)
    newplayer.solid = bool(solid)
    newplayer.growth = float(growth)
    newplayer.bot = bool(bot)
    newplayer.guser = user
    newplayer.lastdividenddate = lastdividenddate
    newplayer.lastdividendamount = float(lastdividendamount)
    newplayer.points = int(points)
    newplayer.levelname = levelname
    newplayer.level = level
    newplayer.alerts = alerts
    newplayer.alertsarchive = alertsarchive
    newplayer.about = about
    newplayer.friends = friends
    newplayer.totalinvestedamount = float(totalinvestedamount)
    newplayer.totalinvestorsamount = float(totalinvestorsamount)
    newplayer.lastlogindate = datetime.datetime.now()
    newplayer.lastpayday = datetime.datetime.now()
    newplayer.occupation = selectoccupationname()
    newplayer.avatar = db.Blob(open("defaultavatar.png", "rb").read())
    newplayer.avatarmedium = db.Blob(images.resize(open("defaultavatar.png", "rb").read(), 60, 60))
    newplayer.avatarsmall = db.Blob(images.resize(open("defaultavatar.png", "rb").read(), 30, 30))
    newplayer.bgselection = bgselection
    newplayer.locked = locked
    newplayer.taxes = taxes
    newplayer.messages = messages
    newplayer.messagearchive = messagearchive
    
    #newplayer.setinvestments({})
    #newplayer.setinvestees({})
    #newplayer.stuff = []
    
    newplayer.put()
    
    return newplayer
Esempio n. 29
0
    def mark_img_init(self):
        if self.black_img == ():
            logging.info('Loading Black Image...')
            f = open("img/black.png", "rb")
            img = f.read()
            f.close()
            self.black_img = (img, images.rotate(img, 180), images.resize(img, 16, 16) )

        if self.white_img == ():
            logging.info('Loading White Image...')
            f = open("img/white.png", "rb")
            img = f.read()
            f.close()
            self.white_img = (img, images.rotate(img, 180), images.resize(img, 16, 16) )
Esempio n. 30
0
  def post(self):
    if ( self.request.get("img1") ):
      PresentTCard = TblCard.all()
      PresentTCard.order('CardNum').fetch(limit=1)
      NextId = 0
      for r in PresentTCard:
        if PresentTCard:
          NextId = r.CardNum + 1
        else:
          NextId = 0
      TCard = TblCard()
      TCard.CardNum = NextId
      if self.request.get("name1"):
        TCard.CardName = self.request.get("name1")
      else:
        TCard.CardName = u"aainc member"
      if self.request.get("desc1"):
        TCard.CardDesc = self.request.get("desc1")
      else:
        TCard.CardDesc = u"thanks"

      Img = images.resize(self.request.get("img1").decode('base64'),600,600)


      framePath = 'http://' + os.environ['HTTP_HOST'] + self.request.get("framePath")

      try:
        ImgFrame = images.resize(urlfetch.Fetch(framePath).content,600,600)
      except:
        time.sleep(3)
        ImgFrame = images.resize(urlfetch.Fetch(framePath).content,600,600)
        try:
          ImgFrame = images.resize(urlfetch.Fetch(framePath).content,600,600)
        except:
          time.sleep(3)
          ImgFrame = images.resize(urlfetch.Fetch(framePath).content,600,600)

      ImgComp = images.composite([(Img,0,0,1.0,0),(ImgFrame,0,0,1.0,0)],600,600)
      TCard.CardImage = db.Blob(ImgComp)

      TCard.CardDate = datetime.datetime.today() + datetime.timedelta(hours=9)
      TCard.CardIPAddress = os.environ['REMOTE_ADDR']

      db.put(TCard)

      cUrl = "/Detail?cid=" + str( TCard.CardNum )
      self.response.out.write( cUrl )

    else:
      self.response.out.write( "/Err" )
Esempio n. 31
0
def get_property_image(request, id, index, thumb):
    property_offer = PropertyOffer.objects.get(id=id)
    image = None
    index = int(index)

    logging.info(index)

    if property_offer:
        if index == 1:
            image = property_offer.image1
        elif index == 2:
            image = property_offer.image2
        elif index == 3:
            image = property_offer.image3
        elif index == 4:
            image = property_offer.image4
        elif index == 5:
            image = property_offer.image5

    if image != None:
        if thumb:
            image = images.resize(image, 100) #, output_encoding=images.JPEG)
        response = HttpResponse(image)
        response['Content-Type'] = 'image/jpeg'
    else:
        return HttpResponseRedirect("/static/image_not_found.png")

    return response
Esempio n. 32
0
 def post(self):
   user = self.user_model
   avatar = self.request.get('img')
   avatar = images.resize(avatar, 400, 400)
   user.avatar = avatar
   user.put()
   self.redirect('/profile/{}'.format(user.username))
Esempio n. 33
0
    def get(self, full_count, unknown_count, empty_count):
        fc = int(full_count)
        uc = int(unknown_count)
        ec = int(empty_count)

        total = fc + uc + ec
        multiplier = 1.0 * total_width / total

        full_pos = int(round(fc * multiplier))
        unknown_pos = int(round(uc * multiplier))
        empty_pos = int(round(ec * multiplier))

        if full_pos < height:
            full_width = height
        else:
            full_width = full_pos

        if unknown_pos < height:
            unknown_width = height
        else:
            unknown_width = unknown_pos

        if empty_pos < height:
            empty_width = height
        else:
            empty_width = empty_pos

        full = images.resize(red_png,
                             full_width,
                             full_width,
                             output_encoding=images.PNG)
        unknown = images.resize(yellow_png,
                                unknown_width,
                                unknown_width,
                                output_encoding=images.PNG)
        empty = images.resize(green_png,
                              empty_width,
                              empty_width,
                              output_encoding=images.PNG)

        full_in = (full, 0, 0, 1.0, images.TOP_LEFT)
        unknown_in = (unknown, full_pos, 0, 1.0, images.TOP_LEFT)
        empty_in = (empty, full_pos + unknown_pos, 0, 1.0, images.TOP_LEFT)
        inputs = (full_in, unknown_in, empty_in)

        self.response.headers['Content-Type'] = 'image/png'
        self.response.out.write(images.composite(inputs, total_width, height))
Esempio n. 34
0
    def post(self):
        file_response = {}

        title = self.request.get('title[]')
        if title is not None:
            title = title.strip()
        description = self.request.get('description[]')
        if description is not None:
            description = description.strip()
        filename = self.request.POST.get('userfile').filename
        art_image = self.request.get('userfile')
        file_size = len(art_image)

        file_response['name'] = filename
        file_response['size'] = file_size
        error = None

        application_user_id = None
        google_user = users.get_current_user()

        if not google_user:
            error = 'You must login before you can POST an image to /upload'
        else:
            google_user_id = google_user.user_id()
            if not google_user_id:
                error = 'You must login before you can POST an image to /upload'
            else:
                application_user = User.get_user_by_google_user_id(
                    google_user_id)
                if not application_user:
                    error = 'You must register before you can POST an image to /upload'
                else:
                    application_user_id = application_user.application_user_id
                    if not application_user_id:
                        error = 'You must register before you can POST an image to /upload'

        if error is not None:
            file_response['error'] = error
            self.response.status = '401 Unauthorized'
        else:
            new_art = Art()
            new_art.title = title
            new_art.description = description
            new_art.application_user_id = application_user_id
            new_art.image = images.resize(art_image, 600, 600)
            new_key = new_art.put()

            new_image_url = self.request.application_url
            if not re.match(r"^.*/$", new_image_url):
                new_image_url += '/'
            new_image_url += 'image/' + new_key.urlsafe()

            file_response['url'] = new_image_url
            file_response['thumbnail_url'] = new_image_url

        response_body = {"files": [file_response]}

        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.dumps(response_body))
Esempio n. 35
0
 def get(self):
     keyid = self.request.get("img_id")
     content = Content.get_by_id(int(keyid))
     if content.thumbnail:
         self.response.headers['Content-Type'] = "image/jpg"
         self.response.out.write(images.resize(content.thumbnail, 175, 84))
     else:
         self.response.out.write("no image")
Esempio n. 36
0
def image_Transform(imageData, width, heigh):
    img = images.Image(imageData)
    img._update_dimensions()
    thumb = imageData
    if img._height > width or img._width > heigh:
        thumb = images.resize(imageData, width, heigh)
    #            thumb = img.execute_transforms(output_encoding=images.JPEG)
    return thumb
Esempio n. 37
0
 def get(self):
     keyid = self.request.get("img_id")
     content = Content.get_by_id(int(keyid))
     if content.photo:
         self.response.headers['Content-Type'] = "image/jpg"
         self.response.out.write(images.resize(content.photo, 484, 481))
     else:
         self.response.out.write("no image")
Esempio n. 38
0
 def get(self):
     greeting = db.get(self.request.get("img_id"))
     if greeting.pic:
         self.response.headers['Content-Type'] = "image/png"
         pic = images.resize(greeting.pic, 32, 32)
         self.response.out.write(pic)
     else:
         self.response.out.write("No image")
Esempio n. 39
0
    def post(self):
        title = self.request.get('title')
        blurb = self.request.get('blurb')
        phone = self.request.get('phone')
        image = self.request.get('image')
        email = self.request.get('email')
        price = self.request.get('price')

        image_thumb = images.resize(image, 100, 100)
        image_medium = images.resize(image, 480, 480)
        image_small = images.resize(image, 200, 200)
        billboards = self.request.get('selected_billboards')
        billboards = [db.Key(key) for key in billboards.split(' ')]

        ad = Ad(title=title)
        ad.ip = self.request.remote_addr
        ad.sold = False
        ad.blurb = blurb
        ad.image = db.Blob(image)
        ad.image_thumb = db.Blob(image_thumb)
        ad.image_medium = db.Blob(image_medium)
        ad.image_small = db.Blob(image_small)
        ad.phone = db.PhoneNumber(phone)
        ad.email = db.Email(email)
        ad.price2 = int(price)
        ad.billboards = billboards
        ad.put()

        ad.password = hashlib.md5(SALT + ad.ip + str(ad.key())).hexdigest()
        ad.save()

        for billboard in db.get(billboards):
            billboard.ads.append(ad.key())
            billboard.put()

        path = os.path.join(os.path.dirname(__file__), 'success.html')
        self.response.out.write(
            template.render(
                path, {
                    'ad':
                    ad,
                    'secret_link':
                    'http://%s/ads/%s/edit?password=%s' %
                    (self.request.host, ad.key(), ad.password)
                }))
Esempio n. 40
0
 def loadThumb(self, url, size):
     try:
         buffer = urllib2.urlopen(url).read()
         img = images.resize(buffer, size, size)
         bytes = ByteArray()
         bytes.write(img)
         return bytes
     except:
         return "Image request Error"
Esempio n. 41
0
def smartResize(
    im, w, h
):  #only resize if it isnt a gif.  broken tho, animation is still getting lost...whatevs
    gif = images.Image(im)
    try:
        gif.seek(1)
    except:
        im = images.resize(im, w, h, 1)
    return im
Esempio n. 42
0
 def get(self):
     i_key = ndb.Key(urlsafe=self.request.get('img_id'))
     greeting = i_key.get()
     if greeting.bomma:
         self.response.headers['Content-Type'] = 'image/png'
         greeting.bomma = images.resize(greeting.bomma, 500, 500)
         self.response.out.write(greeting.bomma)
     else:
         self.response.out.write('No image')
Esempio n. 43
0
 def get(self):
     facebookid = self.request.get("img_id")
     account = Account.get_by_facebookid(str(facebookid))
     assert (account)
     if account.thumbnail:
         self.response.headers['Content-Type'] = "image/jpg"
         self.response.out.write(images.resize(account.thumbnail, 50, 50))
     else:
         self.response.out.write("no image")
Esempio n. 44
0
 def post(self):
   greeting = Greeting()
   if users.get_current_user():
       greeting.author = users.get_current_user()
   greeting.content = self.request.get("content")
   avatar = images.resize(self.request.get("img"), 64, 64)
   greeting.avatar = db.Blob(avatar)
   greeting.put()
   self.redirect('/guestbook/')
Esempio n. 45
0
    def post(self):
        """ Makes changes to an already existing resource as per user input """
        user = users.get_current_user()
        if user:
            rid = self.request.get('resourceID')
            resourceName = self.request.get('resourceName').strip()
            availableStartTime = self.request.get('availableStartTime')
            availableEndTime = self.request.get('availableEndTime')
            tags = self.request.get('tags').strip()
            capacity = self.request.get('capacity')
            description = self.request.get('description').strip()
            avatar = self.request.get('img')

            tempTagsArray = tags.split(",")
            tagsSet = set()
            for tag in tempTagsArray:
                tagsSet.add(tag.strip())

            resource = getResourceByResourceID(rid)
            resource.resourceName = resourceName
            resource.availableStartTime = availableStartTime
            resource.availableEndTime = availableEndTime
            resource.tags = tagsSet
            resource.capacity = int(capacity)
            if description and description.strip():
                resource.description = description.strip()
            else:
                resource.description = None
            if avatar:
                avatar = images.resize(avatar, 32, 32)
                resource.avatar = avatar

            resource.put()

            message = resource.resourceName + " has been edited."
            allResources = getAllResources()
            userResources = getUserResourcesByUserID(user.user_id())
            userReservations = getReservationsByUserID(user.user_id())

            url = users.create_logout_url(self.request.uri)
            template_values = {
                'user': user,
                'allResources': allResources,
                'userResources': userResources,
                'userReservations': userReservations,
                'url': url,
                'displayAllSections': True,
                'width': 14,
                'message': message
            }
            template = JINJA_ENVIRONMENT.get_template('index.html')
            self.response.write(template.render(template_values))

        else:
            url = users.create_login_url(self.request.uri)
            self.redirect(url)
Esempio n. 46
0
 def post(self):
     user_id = users.get_current_user().user_id()
     ludo = SessionData.query(SessionData.user == user_id).get()
     avatar = self.request.get('img')
     logging.debug("starting imageHandler")
     logging.debug(avatar)
     avatar = images.resize(avatar, 128, 128)
     ludo.avatar = avatar
     ludo.put()
     self.redirect('/')
Esempio n. 47
0
    def post(self):
        "Upload via a multitype POST message"

        img = self.request.get("img")

        # if we don't have image data we'll quit now
        if not img:
            self.redirect('/')
            return

        # we have image data
        try:
            # check we have numerical width and height values
            width = int(self.request.get("width"))
            height = int(self.request.get("height"))
        except ValueError:
            # if we don't have valid width and height values
            # then just use the original image
            image_content = img
        else:
            # if we have valid width and height values
            # then resize according to those values
            image_content = images.resize(img, width, height)

        # get the image data from the form
        original_content = img
        # always generate a thumbnail for use on the admin page
        thumb_content = images.resize(img, 100, 100)

        # create the image object
        image = Image()
        # and set the properties to the relevant values
        image.image = db.Blob(image_content)
        # we always store the original here in case of errors
        # although it's currently not exposed via the frontend
        image.original = db.Blob(original_content)
        image.thumb = db.Blob(thumb_content)
        image.user = users.get_current_user()

        # store the image in the datasore
        image.put()
        # and redirect back to the admin page
        self.redirect('/')
Esempio n. 48
0
    def update_image(self):

        image_type, width, height = getimageinfo.getImageInfo(self.file)
        self.mimetype = image_type
        self.image_size = '%d,%d' % (width, height)
        width, height = self.getRoot().thumbnail_size
        thumbnail = images.resize(self.file, width, height, images.JPEG)
        self.image_thumbnail = db.Blob(thumbnail)
        image_type, width, height = getimageinfo.getImageInfo(thumbnail)
        self.thumbnail_size = '%d,%d' % (width, height)
Esempio n. 49
0
 def get(self):
     user = users.get_current_user()
     v_item = self.request.get('item_id', default_value = '')
     if (v_item <> ''):
         v_photo = db_photo(parent=db_item_key(user.user_id()))
         v_photo.id = v_item
         v_photo.user = user.user_id()
         v_photo.avatar = images.resize(self.request.get('img'), 800, 600)
         v_photo.primary = false
         v_photo.put()
    def post(self):
        token = get_request_value(self.request, 'token')
        data = get_request_value(self.request, 'upload')
        key = get_request_value(self.request, 'id')
        user = securityservice.SecurityService.authenticate_user_token(token)

        if key is None:
            key = utils.new_key()
            logging.info('No id in request: %s', key)

        #logging.info(self.request)
        if user and data:  # and len(data)<=2097152:
            file = datamodel.UploadedFile(key_name=key)
            file.ip = self.request.remote_addr

            file.fileName = self.request.POST.get('upload').filename
            if not file.fileName:
                file.fileName = str(uuid.uuid1())
            logging.info(file.fileName)

            file.fileType = None  #self.request.headers.get('Content-Type')
            if not file.fileType:
                file.fileType = 'image/png'
            logging.info(file.fileType)

            if 'image' in file.fileType:
                img = images.Image(data)
                file.width = img.width
                file.height = img.height

            if len(data) <= 524288 and 'image' in file.fileType:
                file.thumbnailBlob = db.Blob(images.resize(data, 96, 96))

            file.fileBlob = db.Blob(data)
            file.fileSize = len(data)
            file.owner = user.name
            file.is_deleted = False
            file.updated = datetime.datetime.now()
            file.bookmark = utils.bookmark_for_kind(datatype, user.name,
                                                    file.updated)
            file.put()

            file.url = '/assets?id=%s' % (file.key())
            if file.thumbnailBlob:
                file.thumbnail = '/assets?id=%s&size=thumbnail' % (file.key())
            file.put()

            json_ret = '{"status": "0", "id": "%s", "url": "%s"}' % (key,
                                                                     file.url)
            self.response.out.write(json_ret)

        else:
            logging.error(
                'File upload failed, upload key is missing or file size > 2MB')
            self.error(401)
Esempio n. 51
0
 def post(self):
     picture = Picture()
     picture.image = images.resize(self.request.get('image'), 250, 250)
     # picture_key = picture.put()
     picture_key = picture.put()
     trip = Trip()
     trip.name = self.request.get('trip')
     trip.pictures = [picture_key]
     # trip.pictures=[picture_key]
     trip.put()
     self.redirect("/newpicture")
        def post_process_model(filled_student_officer):
            filled_student_officer.Image = images.resize(filled_student_officer.Image, 100, 196)

            if not filled_student_officer.DisplayOrder:
                # TODO: only get DisplayOrder
                # displayOrderObject = GqlQuery("SELECT DisplayOrder FROM StudentOfficer ORDER BY DisplayOrder DESC").get()
                displayOrderObject = StudentOfficer.gql("ORDER BY DisplayOrder DESC").get()
                if displayOrderObject and displayOrderObject.DisplayOrder:
                    filled_student_officer.DisplayOrder = displayOrderObject.DisplayOrder + 1
                else:
                    filled_student_officer.DisplayOrder = 1
Esempio n. 53
0
 def post(self):
     user=UptradeUser.get_by_id(users.get_current_user().user_id())
     new=Product(
     name=self.request.get("nam"),
     description=self.request.get("desc"),
     photo=images.resize(self.request.get("pic"),350,350),
     category=self.request.get("cat"),
     seller=user.put()).put()
     user.products.append(new)
     user.put()
     self.redirect("/")
Esempio n. 54
0
    def post(self):

        unicorn = self.request.get('file')
        img_name = self.request.POST['file'].filename
        # img_name = "ohshitfuck"  # self.request.get('img_name')
        stream_id = self.request.get('stream_id')  # self.request.get('stream_id')

        unicorn = images.resize(unicorn, 500, 500)
        # find the right bucket-stream path
        b = "/pigeonhole-apt.appspot.com/" + str(stream_id)

        # much be post!
        img_real_name = self.request.POST['file'].filename
        pat = "(.+)\.(.+)"
        img_real_type = re.match(pat, str(img_real_name)).group(2)

        # construct a new content_type
        content_type_value = "image/" + str(img_real_type).lower()

        # create such file and write to it
        gcs_file = gcs.open(b + "/" + str(img_name), 'w', content_type=content_type_value)
        gcs_file.write(unicorn)
        gcs_file.close()

        unicorn_url = "https://storage.googleapis.com/pigeonhole-apt.appspot.com/" \
                      + str(stream_id) + "/" + str(img_name)

        """
        unicorn_url = self.request.get('img_url')
        img_name = self.request.get('img_name')
        stream_id = self.request.get('stream_id')
        """

        # img_comment = "comment"
        # ops.create_image(img_comment, img_name, unicorn_url, stream_id)
        # # self.redirect(str("https://pigeonhole-apt.appspot.com/view_single?stream_id=" + str(stream_id)))
        lat = - 57.32652122521709 + 114.65304245043419 * random.random()
        lon = - 123.046875 + 246.09375 * random.random()

        form_fields = {
            'img_url': unicorn_url,
            'img_name': str(re.match(pat, str(img_real_name)).group(1)),
            'stream_id': stream_id,
            'lon': lon,
            'lat': lat
        }

        form_data = urllib.urlencode(form_fields)
        headers = {}  # {'Content-Type': 'multipart/form-data'}
        # headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        result = urlfetch.fetch(
            url='https://services-dot-pigeonhole-apt.appspot.com/service-secretupload',  # need changing
            payload=form_data,
            method=urlfetch.POST)
Esempio n. 55
0
    def post(self):
        avatar = self.request.get('image')

        avatar = images.resize(avatar, 500, 500)
        current_user = get_logged_in_user(self)

        this_image = Image(image=avatar)
        img_id = this_image.put()
        current_user.image_model = img_id
        current_user.put()
        self.redirect('/info_update')
Esempio n. 56
0
    def post(self):
        id = int(self.request.uri.split('/')[-1])
        if self.request.get('pic'):
            photo = DBPhoto()
            image = images.Image(self.request.get('pic'))
            image_resized = images.Image(
                images.resize(
                    image._image_data, width=130, output_encoding=images.JPEG)
            ) if image.height >= image.width else images.Image(
                images.resize(image._image_data,
                              height=130,
                              output_encoding=images.JPEG))
            image_cropped = images.crop(
                image_resized._image_data, 0.0, 0.0,
                float(130) / float(image_resized.width), 1.0,
                images.JPEG) if image_resized.height == 130 else images.crop(
                    image_resized._image_data, 0.0, 0.0, 1.0,
                    float(130) / float(image_resized.height), images.JPEG)
            photo.image_small = db.Blob(image_cropped)
            if (image.width < 400 and image.height < 400
                ) or image.width > 1024 or image.height > 768:
                self.insertContent(
                    "Фотография не должна быть больше 1024 пикселей в ширину и 768 пикселей в высоту, но хотя бы одна сторона фотографии должна быть больше 400 пикселей. При этом размер файла с фотографие должен быть не более 1мб."
                )
                self.drawPage()
                return
            photo.image_big = db.Blob(image._image_data)
            #photo.image_big = db.Blob(images.resize(self.request.get('pic'), 1024, 768))
            #photo.tags = self.request.get('tags')
            photo.albumid = id
            secret = str(hashlib.md5(str(random.random())).hexdigest())
            photo.comment = secret
            photo.put()
            photo_temp = DBPhoto.gql("where comment = :comment",
                                     comment=secret)
            tags = DBPhotoTags()
            tags.tags = self.request.get('tags')
            tags.imageid = int(photo_temp[0].key().id())
            tags.put()

        self.redirect("/album/%s" % str(id))
Esempio n. 57
0
    def post(self):
        greeting = Greeting()

        if users.get_current_user():
            greeting.author = users.get_current_user()

        greeting.content = self.request.get('content')
        if self.request.get("img"):
            avatar = images.resize(self.request.get("img"), 32, 32)
            greeting.avatar = db.Blob(avatar)
        greeting.put()
        self.redirect('/')
Esempio n. 58
0
 def post(self):
     add_item = self.request.get('img')
     stream_query = Stream.query(
         Stream.name == self.request.get('stream_name')).fetch()
     imag_item = Imag(parent=stream_query[0].key)
     imag_item.item = images.resize(add_item, 100, 100)
     imag_item.put()
     query_params = {
         'stream_id': stream_query[0].key.id(),
         'stream_name': stream_query[0].name
     }
     self.redirect('/viewsinglestream?' + urllib.urlencode(query_params))
Esempio n. 59
0
def outer_heaven(request):
    filelist=UserFile.all().order('-creationDate').fetch(FILE_MAX)
    for file in filelist:
        if not file.icon:
            try :
                filebin=file.filebin_set.get()
                file.icon=images.resize(filebin.bin, width=60)
                file.put()
            except:
                pass
    
    return render_to_response('upload/OuterHeaven.html',locals(),context_instance=RequestContext(request))
Esempio n. 60
0
 def post(self):
     project_id = str(uuid.uuid1())
     picture = images.resize(self.request.get('file'), 100)
     logo = ProjectLogo(project_id=project_id, picture=picture)
     logo.put()
     self.response.headers['Content-Type'] = 'application/json'
     self.response.set_status(201)
     self.response.out.write(
         json.dumps({
             'success': True,
             'project_id': project_id
         }))