def create_meme(top, bottom, meme, template_uid): """Create a meme object in the datastore""" m = Image(meme) thumb = Image(meme) width, height = m.width, m.height if m.width != 500: m.resize(width=500) m = m.execute_transforms(output_encoding=JPEG) moar_img_data = Image(m) width, height = moar_img_data.width, moar_img_data.height meme = db.Blob(m) else: logging.info("There") meme = db.Blob(meme) thumb.resize(height=125) thumb = thumb.execute_transforms(quality=85,output_encoding=JPEG) thumb = db.Blob(thumb) meme = Meme(uid=str(get_meme_url()), top=top, bottom=bottom, meme=meme, meme_width=width, meme_height=height, thumb=thumb, template_uid=template_uid) meme.put() return meme
def create_template(name, img): """Adds this template to the datastore along with a generated thumbnail and accompanied dimension metadata""" thumb = Image(img) template_data = Image(img) t_img = db.Blob(img) width, height = template_data.width, template_data.height if width != 500: template_data.resize(width=500) template_data = template_data.execute_transforms() t_data = Image(template_data) width, height = t_data.width, t_data.height t_img = db.Blob(template_data) thumb.resize(height=125) thumb = thumb.execute_transforms(quality=75,output_encoding=JPEG) t = Template(uid=generate_uuid(16), name=name, img=t_img, thumb=db.Blob(thumb), real_width=width, real_height=height) t.put()
def process_image(self, image_data, width, height, quality): img = Image(image_data=image_data) try: img.resize(width=width) return img.execute_transforms(output_encoding=JPEG, quality=quality) except NotImageError: return image_data
def post(self): img = Image(self.request.get('file')) json = self.request.get('json', False) height = int(self.request.get('height', default_value='1')) width = int(self.request.get('width', default_value='1')) img.resize(width, height) resized = img.execute_transforms() self.render(image=resized, data={'height':height, 'width':width})
def _to_base_type(self, value): """ Transforming the image and saving it to blobstore """ img = Image(self._img_data) if self._width > 0 or self._height > 0: img.resize(width=self._width, height=self._height) img.im_feeling_lucky() return img.execute_transforms(output_encoding=images.JPEG)
def testImage(self): """Creates an image object from blob data.""" from google.appengine.api.images import Image query = blobstore.BlobInfo.all() key = str(query.fetch(1).pop().key()) img = Image(blob_key=key) img.resize(width=200) data = img.execute_transforms() thumbnail = Image(data) self.assertEqual(200, thumbnail.width)
def post(self): key = int(self.request.get('key')) photo = Photo.get_by_id(key) raw_image = Image(blob_key=photo.photo_blob_key) raw_image.resize(128, 128) thumbnail = raw_image.execute_transforms() photo.thumbnail = thumbnail photo.thumbnailed = True photo.put()
def make_reduced_image(data): img = Image(data) if not (img.width > settings.FEATURE_MAX_W and img.height > settings.FEATURE_MAX_H): return data w_pct = settings.FEATURE_MAX_W / float(img.width) h_pct = settings.FEATURE_MAX_H / float(img.height) if h_pct < w_pct: pct = h_pct else: pct = w_pct img.resize(int(pct * img.width), int(pct * img.height)) return img.execute_transforms(JPEG)
def resize_image(image_data, width, height): image = Image(image_data=image_data) if (image.width / float(width)) > (image.height / float(height)): image.resize(height=height) image = Image(image_data=image.execute_transforms()) x_crop_ratio = (image.width - width) / float(image.width * 2) image.crop(x_crop_ratio, 0.0, 1 - x_crop_ratio, 1.0) else: image.resize(width=width) image = Image(image_data=image.execute_transforms()) y_crop_ratio = (image.height - height) / float(image.height * 2) image.crop(0.0, y_crop_ratio, 1.0, 1 - y_crop_ratio) return image.execute_transforms()
def make_image_thumbnail(data): img = Image(data) if img.width > img.height: size = img.height else: size = img.width left = ((img.width - float(size)) / img.width) / 2 top = ((img.height - float(size)) / img.height) / 2 #raise Exception('left %f top %f' % (left, top)) img.crop(left, top, 1.0 - left, 1.0 - top) img.resize(settings.THUMBNAIL_SIZE, settings.THUMBNAIL_SIZE) return img.execute_transforms(JPEG)
def store_picture_from_content(cls, blob_key): """ Resize picture and upload to Cloud Storage bucket. Return the GCS key """ data = blobstore.BlobReader(blob_key).read() img = Image(data) img.resize(width=800, height=600) # img.im_feeling_lucky() img = img.execute_transforms(output_encoding=JPEG) new_gcs_key = cls.upload_blob_to_gcs(img, content_type='img/jpeg') # delete original blob delete_serving_url(blob_key) blobstore.delete(blob_key) return new_gcs_key
def trans(image): changed_properties = [] user_profile = get_user_profile(app_user) if name is not MISSING: if user_profile.name != name: changed_properties.append(u"name") user_profile.name = name # has_birthdate and has_gender are used starting from 1.0.999.A and 1.0.137.i if has_birthdate is not MISSING and has_gender is not MISSING: if has_birthdate is True: user_profile.birthdate = birthdate user_profile.birth_day = UserProfile.get_birth_day_int(birthdate) if has_gender is True: user_profile.gender = gender else: # birthdate and gender are only used without has_gender and has_birthdate in 1.0.998.A if birthdate is not MISSING and gender is not MISSING: if birthdate == 0 and gender == 0: pass # user pressed save in 1.0.998.A without setting gender and birthdate else: user_profile.birthdate = birthdate user_profile.birth_day = UserProfile.get_birth_day_int(birthdate) if gender != 0: user_profile.gender = gender if image: avatar = get_avatar_by_id(user_profile.avatarId) if not avatar: avatar = Avatar(user=user_profile.user) image = base64.b64decode(str(image)) img = Image(image) if img.width > 150 or img.height > 150: logging.info('Resizing avatar from %sx%s to 150x150', img.width, img.height) img.resize(150, 150) image = img.execute_transforms(img.format, 100) update_avatar_profile(user_profile, avatar, image) changed_properties.append(u"avatar") user_profile.version += 1 user_profile.put() from rogerthat.bizz.profile import update_mobiles, update_friends update_mobiles(user_profile.user, user_profile, current_mobile) # update myIdentity schedule_re_index(app_user) if changed_properties: # Not necessary when only birth date or gender were updated. update_friends(user_profile) # notify my friends.
def get(self, key): try: photo = ndb.Key(urlsafe=key).get() if photo: self.response.headers['Content-Type'] = 'image/png' self.response.out.write(photo.get_thumb()) else: default_thumb = memcache.get('DEFAULT-THUMB') if not default_thumb: default_thumb = Image() default_thumb.resize(65,55) self.response.headers['Content-Type'] = 'image/png' self.response.out.write(default_thumb) memcache.set('DEFAULT-THUMB', default_thumb) except Exception: logging_ext.error('ThumbHandler '+key, exc_info=True)
def store_picture_from_content(content, mime_type='application/octet-stream'): img = Image(content) img.resize(width=800, height=800) img.im_feeling_lucky() img_type = PNG if 'png' in mime_type else JPEG img = img.execute_transforms(output_encoding=img_type) # create file file_name = files.blobstore.create(mime_type=mime_type) with files.open(file_name, 'a') as f: f.write(img) # Finalize the file files.finalize(file_name) # Get the file's blob key blob_key = files.blobstore.get_blob_key(file_name) return get_serving_url(blob_key), blob_key
def AddImage(self, image_data, width, height, img_type, instance=None): """ Handle adding an image of the application. Args: image_data: binary blob from an HTTP request. width: the image maximum width in pixels. height: the image maximum height in pixels. img_type: the type of the image (screenshot or thumbnail) instance: a previously stored image for this app, if one exists. """ from google.appengine.api.images import Image imageContent = Image(image_data) imageContent.resize(width, height) if instance is None: image = ApplicationImage() else: image = instance image.application = self image.img_type = img_type image.content = imageContent.execute_transforms() image.put()
def AddImage(self, image_data, width, height, img_type, instance = None): """ Handle adding an image of the application. Args: image_data: binary blob from an HTTP request. width: the image maximum width in pixels. height: the image maximum height in pixels. img_type: the type of the image (screenshot or thumbnail) instance: a previously stored image for this app, if one exists. """ from google.appengine.api.images import Image imageContent = Image(image_data) imageContent.resize(width, height) if instance is None: image = ApplicationImage() else: image = instance image.application = self image.img_type = img_type image.content = imageContent.execute_transforms() image.put()
def get(self, flip_horizontal, width, flip_vertical, height, halign, valign, url): if not url: self._error(400, 'The url argument is mandatory!') return if not width and not height: self._error(400, 'Either width or height are mandatory!') url = join('http://', url) if not self._verify_allowed_domains(): self._error(404, 'Your domain is not allowed!') return if not self._verify_allowed_sources(url): self._error(404, 'Your image source is not allowed!') return width = width and int(width) or 0 height = height and int(height) or 0 if width > MAX_WIDTH: width = MAX_WIDTH if height > MAX_HEIGHT: height = MAX_HEIGHT if not halign: halign = "center" if not valign: valign = "middle" key = "%d_%d_%s_%s_%s" % ( width, height, halign, valign, url ) extension = splitext(url)[-1] image_format = extension in ('.jpg', '.jpeg') and JPEG or PNG data = memcache.get(key) self.response.headers['Cache-Key'] = key if data is not None: results = data self.response.headers['Cache-Hit'] = 'True' else: query = "SELECT * FROM Picture WHERE url = :1 LIMIT 1" pictures = db.GqlQuery(query, url).fetch(1) try: if len(pictures) > 0: picture = pictures[0] if picture.is_expired(): img = picture.fetch_image() picture.put() else: img = Image(picture.picture) else: picture = Picture() picture.url = url img = picture.fetch_image() picture.put() except ImageNotFoundError: self._error(404, 'Your image source is not found!') return if float(width) / float(img.width) > float(height) / float(img.height): img.resize(width=width) image_width = width image_height = float(width) / float(img.width) * float(img.height) else: img.resize(height=height) image_width = float(height) / float(img.height) * float(img.width) image_height = height rect = BoundingRect(height=image_height, width=image_width) rect.set_size(height=height, width=width, halign=halign, valign=valign) if not width: width = rect.target_width if not height: height = rect.target_height img.crop(left_x=rect.left, top_y=rect.top, right_x=rect.right, bottom_y=rect.bottom) if flip_horizontal: img.horizontal_flip() if flip_vertical: img.vertical_flip() results = img.execute_transforms(output_encoding=image_format, quality=QUALITY) memcache.set(key=key, value=results, time=EXPIRATION) # ONE MONTH self.response.headers['Cache-Hit'] = 'False' self.response.headers['Content-Type'] = image_format == JPEG and 'image/jpeg' or 'image/png' self.response.out.write(results)
def calculate_user_values(self, username): memcache_data_key = '!data!{}'.format(username) values = json.loads(memcache.get(memcache_data_key) or '{}') if values: return values try: github_user = User.get(username) except pyresto.Error: self.response.set_status(404) # not 100% sure but good enough self.render('errors/404') return except Exception as err: self.response.set_status(500) logging.error(err) return languages = User.sort_languages(github_user.language_stats) fork_count = sum(1 for repo in github_user.repos if repo.fork) today = datetime.datetime.today() recent_than = today - datetime.timedelta(days=conf.RECENT_DAYS) own_commits = github_user.get_latest_commits(recent_than) commits_by_repo = reduce(self.reduce_commits_by_repo, own_commits, dict()) if commits_by_repo: last_project = max(commits_by_repo, key=commits_by_repo.get) else: last_project = '' logging.info(commits_by_repo) if last_project: last_project_url = [repo.html_url for repo in github_user.repos if repo.name == last_project][0] else: last_project_url = None commits_by_date = reduce(self.reduce_commits_by_date, own_commits, dict()) range = daterange(recent_than, today) for d in range: key = unicode(d.date()) if key not in commits_by_date: commits_by_date[key] = 0 commit_data = [commits_by_date[d] for d in sorted(commits_by_date)] max_commits = max(commit_data) logging.debug('Commit data %s', str(commit_data)) commit_sparkline = data_uri(sparklines.impulse(commit_data, below_color='SlateGray', width=3, dmin=0, dmax=max(commit_data))) try: # try to embed the scaled-down user avatar avatar = Image(urllib2.urlopen(github_user.avatar_url).read()) avatar.resize(24, 24) github_user.avatar_url = data_uri(avatar.execute_transforms()) except (AttributeError, ValueError, urllib2.URLError): pass user_info = dict((k, v) for k, v in github_user.__dict__.iteritems() if k[0] != '_') values = {'user': user_info, 'own_repos': len(github_user.repos) - fork_count, 'fork_repos': fork_count, 'languages': languages, 'project_followers': github_user.project_followers - len(github_user.self_watched), 'commit_sparkline': commit_sparkline, 'max_commits': max_commits, 'last_project': last_project, 'last_project_url': last_project_url, 'days': conf.RECENT_DAYS } if not memcache.set(memcache_data_key, json.dumps(values), conf.MEMCACHE_EXPIRATION): logging.error('Memcache set failed for user data %s', username) return values
def get(self, *groups): id = int(groups[0]) level = int(groups[1]) column = int(groups[2]) row = int(groups[3]) try: gigapan = get_gigapan(id) except: self.error(404) return self.width = gigapan.width self.height = gigapan.height self.tile_overlap = 0 self.tile_size = 256 self._num_levels = None tileserver = str(int(math.floor(id / 1000.0))).zfill(2) url = API_GIGAPAN_TILE_URL%{"tileserver": tileserver, "id": id} name = "r" z = max(0, level - 8) bit = (1 << z) >> 1 x = column y = row while bit > 0: name += str((1 if (x & bit) else 0) + (2 if (y & bit) else 0)) bit = bit >> 1 i = 0 while i < (len(name) - 3): url = url + "/" + name[i:i+3] i = i + 3 tile_url = url + "/" + name + ".jpg" tile_request = fetch(tile_url) image_data = tile_request.content image = Image(image_data) w, h = self.get_dimensions(level) modified = False if level < 8: d = 2**level image.resize(d, d) image.crop(0.0, 0.0, min(w / float(d), 1.0), h / float(d)) modified = True else: tile_x = column * self.tile_size tile_y = row * self.tile_size tile_right = tile_x + self.tile_size tile_bottom = tile_y + self.tile_size if tile_right > w or tile_bottom > h: factor = float(self.tile_size) tile_width = min(w - tile_x, self.tile_size) tile_height = min(h - tile_y, self.tile_size) image.crop(0.0, 0.0, tile_width / factor, tile_height / factor) modified = True if modified: image_data = image.execute_transforms(output_encoding=google.appengine.api.images.JPEG) self.response.headers["Content-Type"] = "image/jpeg" self.response.out.write(image_data)
def calculate_user_values(self, username): memcache_data_key = '!data!{}'.format(username) values = json.loads(memcache.get(memcache_data_key) or '{}') if values: return values try: github_user = User.get(username) except pyresto.PyrestoException: self.response.set_status(404) # not 100% sure but good enough self.render('errors/404') return except Exception as err: self.response.set_status(500) logging.error(err) return languages = User.sort_languages(github_user.language_stats) fork_count = sum(1 for repo in github_user.repos if repo.fork) today = datetime.datetime.today() days_to_go_back = self.app.config['RECENT_DAYS'] recent_than = today - datetime.timedelta(days=days_to_go_back) own_commits = github_user.get_latest_commits(recent_than) commits_by_repo = reduce(self.reduce_commits_by_repo, own_commits, dict()) if commits_by_repo: last_project_id = max(commits_by_repo, key=commits_by_repo.get) else: last_project_id = None logging.info(commits_by_repo) if last_project_id: last_project = [ repo for repo in github_user.repos if repo.full_name == last_project_id ][0] last_project_name = last_project.name last_project_url = last_project.html_url else: last_project_name = '' last_project_url = '' commits_by_date = reduce(self.reduce_commits_by_date, own_commits, dict()) range = daterange(recent_than, today) for d in range: key = unicode(d.date()) if key not in commits_by_date: commits_by_date[key] = 0 commit_data = [commits_by_date[d] for d in sorted(commits_by_date)] max_commits = max(commit_data) logging.debug('Commit data %s', str(commit_data)) commit_sparkline = data_uri( sparklines.impulse(commit_data, below_color='SlateGray', width=3, dmin=0, dmax=max(commit_data))) try: # try to embed the scaled-down user avatar avatar = Image(urllib2.urlopen(github_user.avatar_url).read()) avatar.resize(24, 24) github_user.avatar_url = data_uri(avatar.execute_transforms()) except (AttributeError, ValueError, urllib2.URLError): pass user_info = dict( (k, v) for k, v in github_user.__dict__.iteritems() if k[0] != '_') values = { 'user': user_info, 'own_repos': len(github_user.repos) - fork_count, 'fork_repos': fork_count, 'languages': languages, 'project_followers': github_user.project_followers - len(github_user.self_watched), 'commit_sparkline': commit_sparkline, 'max_commits': max_commits, 'last_project': last_project_name, 'last_project_url': last_project_url, 'days': conf.RECENT_DAYS } if not memcache.set(memcache_data_key, json.dumps(values), self.app.config['MEMCACHE_EXPIRATION']): logging.error('Memcache set failed for user data %s', username) return values
def calculate_user_values(self, username): memcache_data_key = "!data!{}".format(username) values = json.loads(memcache.get(memcache_data_key) or "{}") if values: return values try: github_user = User.get(username) except pyresto.PyrestoException: self.response.set_status(404) # not 100% sure but good enough self.render("errors/404") return except Exception as err: self.response.set_status(500) logging.error(err) return languages = User.sort_languages(github_user.language_stats) fork_count = sum(1 for repo in github_user.repos if repo.fork) today = datetime.datetime.today() days_to_go_back = self.app.config["RECENT_DAYS"] recent_than = today - datetime.timedelta(days=days_to_go_back) own_commits = github_user.get_latest_commits(recent_than) commits_by_repo = reduce(self.reduce_commits_by_repo, own_commits, dict()) if commits_by_repo: last_project_id = max(commits_by_repo, key=commits_by_repo.get) else: last_project_id = None logging.info(commits_by_repo) if last_project_id: last_project = [repo for repo in github_user.repos if repo.full_name == last_project_id][0] last_project_name = last_project.name last_project_url = last_project.html_url else: last_project_name = "" last_project_url = "" commits_by_date = reduce(self.reduce_commits_by_date, own_commits, dict()) range = daterange(recent_than, today) for d in range: key = unicode(d.date()) if key not in commits_by_date: commits_by_date[key] = 0 commit_data = [commits_by_date[d] for d in sorted(commits_by_date)] max_commits = max(commit_data) logging.debug("Commit data %s", str(commit_data)) commit_sparkline = data_uri( sparklines.impulse(commit_data, below_color="SlateGray", width=3, dmin=0, dmax=max(commit_data)) ) try: # try to embed the scaled-down user avatar avatar = Image(urllib2.urlopen(github_user.avatar_url).read()) avatar.resize(24, 24) github_user.avatar_url = data_uri(avatar.execute_transforms()) except (AttributeError, ValueError, urllib2.URLError): pass user_info = dict((k, v) for k, v in github_user.__dict__.iteritems() if k[0] != "_") values = { "user": user_info, "own_repos": len(github_user.repos) - fork_count, "fork_repos": fork_count, "languages": languages, "project_followers": github_user.project_followers - len(github_user.self_watched), "commit_sparkline": commit_sparkline, "max_commits": max_commits, "last_project": last_project_name, "last_project_url": last_project_url, "days": conf.RECENT_DAYS, } if not memcache.set(memcache_data_key, json.dumps(values), self.app.config["MEMCACHE_EXPIRATION"]): logging.error("Memcache set failed for user data %s", username) return values