def get(self): project_id = self.request.get('project_id') metadata = self.request.get('metadata') resize = self.request.get('resize') rotate = self.request.get('rotate') transform = self.request.get('transform') query = db.GqlQuery("SELECT * FROM ProjectLogo WHERE " "project_id = '%s'" % project_id) logo = query[0] if metadata is not None and metadata == 'true': if transform is not None and transform == 'true': logo_image = images.Image(logo.picture) if resize is not None and len(resize) > 0: logo_image.resize(width=int(resize)) if rotate is not None and rotate == 'true': logo_image.rotate(90) logo_image.execute_transforms() else: self.response.headers['Content-Type'] = 'application/json' if resize is not None and len(resize) > 0: logo.picture = images.resize(logo.picture, width=int(resize)) if rotate is not None and rotate == 'true': logo.picture = images.rotate(logo.picture, 90) logo_image = images.Image(logo.picture) image_data = { 'height': logo_image.height, 'width': logo_image.width, 'format': logo_image.format } self.response.out.write(json.dumps(image_data)) else: self.response.headers['Content-Type'] = 'image/png' self.response.out.write(str(logo.picture))
def make_thumb(self): window_ratio = 65.0 / 55.0 height = images.Image(image_data=self.picture).height width = images.Image(image_data=self.picture).width image_ratio = float(width) / float(height) logging.info("thumb " + str(image_ratio)) if image_ratio > window_ratio: # wide new_height = 55 new_width = int(55.0 * image_ratio) self.thumb = images.resize(self.picture, new_width, new_height, output_encoding=images.JPEG, quality=55, correct_orientation=CORRECT_ORIENTATION) self.thumb = images.crop(self.thumb, left_x=0.5 - 32.0 / new_width, top_y=0.0, right_x=0.5 + 32.0 / new_width, bottom_y=1.0) else: new_width = 65 new_height = int(65.0 / image_ratio) self.thumb = images.resize(self.picture, new_width, new_height, output_encoding=images.JPEG, quality=55, correct_orientation=CORRECT_ORIENTATION) self.thumb = images.crop(self.thumb, left_x=0.0, top_y=0.5 - 27.0 / new_height, right_x=1.0, bottom_y=0.5 + 27.0 / new_height)
def post(self,gallery_slug): image = images.Image(self.request.get("img")) thumb = images.Image(self.request.get("img")) aspect_ratio = float(image.width) / float(image.height) # crop the image to make it square for the thumb if aspect_ratio > 1.0: left_x = float(image.width-image.height)/float(2*image.width) right_x = float(image.height+image.width)/float(2*image.width) thumb.crop(left_x,0.0,right_x,1.0) elif aspect_ratio < 1.0: top_y = float(image.height-image.width)/float(2*image.height) bottom_y = float(image.height+image.width)/float(2*image.height) thumb.crop(0.0,top_y,1.0,bottom_y) thumb.resize(45,45) image.resize(800,600) # find gallery that we are adding to gallery = db.Query(Gallery).filter('slug =',gallery_slug).get() # is the photo to be displayed on the front page as well? fp = self.request.get("frontpage",False) if fp: fp = True # create and save the new photo new_photo = Photo( title = self.request.get("title"), image_data = db.Blob(image.execute_transforms()), thumb_data = db.Blob(thumb.execute_transforms()), extension = 'png', gallery = gallery, frontpage = fp, ) new_photo.put() #self.redirect('/gallery/%s/view'%gallery_slug) return self._compose(gallery_slug,['New photo "%s" added to gallery "%s".'%(new_photo.title,gallery.title)])
def get(self, version='v1'): image_id = self.request.get('id') if image_id == '': return self.error(404) if version not in ('v1', 'v2', 'v3'): return self.error(501) if len(image_id) == 6: image_id = hashlib.md5('%s-%s' % (SECRET_IMAGE_KEY, image_id)).hexdigest() thumbnail = memcache.get('cached_original_%s_%s' % (version, image_id)) if thumbnail is None: original_image_query = OriginalImage().all() original_image_query.filter('access_key =', image_id) original_image = original_image_query.get() if original_image is None: memcache.add('cached_original_%s_%s' % (version, image_id), 404, 3600) return self.error(404) if original_image.archive_list_key.delete_flg: memcache.add('cached_original_%s_%s' % (version, image_id), 404, 3600) return self.error(404) img = images.Image(original_image.image) if version == 'v2': img.resize(width=640) #img.im_feeling_lucky() thumbnail = img.execute_transforms(output_encoding=images.PNG) thumbnail = convert_square(thumbnail, 640, 640) # Workaround img = images.Image(thumbnail) img.resize(width=640) thumbnail = img.execute_transforms(output_encoding=images.JPEG) else: img.resize(width=320) #img.im_feeling_lucky() thumbnail = img.execute_transforms(output_encoding=images.JPEG) #thumbnail = convert_square(thumbnail, 320, 320) memcache.add('cached_original_%s_%s' % (version, image_id), thumbnail, 3600) logging.info('Original from DB. id: %s' % image_id) else: logging.info('Original from memcache. id: %s' % image_id) if thumbnail == 404: return self.error(404) self.response.headers['Content-Type'] = 'image/jpeg' self.response.out.write(thumbnail)
def get(self): id = int(self.request.uri.split('/')[-1]) entity = int(self.request.uri.split('/')[-2]) dowatermark = True if str( self.request.uri.split('/')[-3]) == "watermark" else False docrop = True if str( self.request.uri.split('/')[-3]) == "crop" else False cropsize = int(self.request.uri.split('/')[-4]) if docrop else 100 watermark = WaterMark() try: self.query = self.__entities[entity].get_by_id(id) except: tquery = db.GqlQuery(self.__entities[entity], queryid=id) self.query = tquery.fetch(1)[0] if self.query: self.response.headers['Content-Type'] = 'image/jpeg' self.response.headers['Expires'] = "Thu,01 Jan 2020 00:00:01 GMT" self.response.headers['Cache-Control'] = "public" if entity == 3: image = watermark.insert( self.query.image_small ) if dowatermark else self.query.image_small self.response.out.write(image) elif entity == 4: image = watermark.insert( self.query.image_big ) if dowatermark else self.query.image_big self.response.out.write(image) else: image = images.Image(self.query.image) image_resized = images.Image( images.resize(image._image_data, width=cropsize, output_encoding=images.JPEG) ) if image.height >= image.width else images.Image( images.resize(image._image_data, height=cropsize, output_encoding=images.JPEG)) image_cropped = images.crop( image_resized._image_data, 0.0, 0.0, float(cropsize) / float(image_resized.width), 1.0, images. JPEG) if image_resized.height == cropsize else images.crop( image_resized._image_data, 0.0, 0.0, 1.0, float(cropsize) / float(image_resized.height), images.JPEG) # image = images.Image(images.resize(self.query.image, height=cropsize, output_encoding=images.JPEG)) # if image.width > image.height: # self.imagec = images.crop(image._image_data, 0.0, 0.0, float(cropsize)/float(image.width), 1.0, images.JPEG) # else: self.imagec = image._image_data self.response.out.write( image_cropped if docrop else self.query.image)
def maybe_process_image(image_url, crop_tuple, base_name): if CLOUD_STORAGE_ROOT_URL in image_url and crop_tuple == NO_CROP_TUPLE: return (image_url, None) image_result = urlfetch.fetch(image_url) if image_result.status_code < 200 or image_result.status_code >= 300: raise IOError('Error downloading image: HTTP %d.' % image_result.status_code) filename = re.sub(r'[^\w]+', '-', base_name.strip().lower()) + '.jpg' # main image image_gcs_path = CLOUD_STORAGE_BASE_PATH + '/fullres/' + filename # resize to max width 4000 or max height 2000 image_contents = image_result.content image = images.Image(image_contents) edited = False if image.height > 2000: image.resize(width=(image.width * 2000 / image.height), height=2000) edited = True elif image.width > 4000: image.resize(width=4000, height=(image.height * 4000 / image.width)) edited = True if crop_tuple != NO_CROP_TUPLE: image.crop(*crop_tuple) edited = True if edited: image_contents = image.execute_transforms(output_encoding=images.JPEG, quality=80) # upload with default ACLs set on the bucket # or use options={'x-goog-acl': 'public-read'}) gcs_file = gcs.open(image_gcs_path, 'w', content_type='image/jpeg') gcs_file.write(image_contents) gcs_file.close() # thumb thumb_gcs_path = CLOUD_STORAGE_BASE_PATH + '/thumbs/' + filename thumb = images.Image(image_result.content) thumb.resize(width=(thumb.width * THUMB_HEIGHT / thumb.height), height=THUMB_HEIGHT) if crop_tuple != NO_CROP_TUPLE: thumb.crop(*crop_tuple) edited = True thumb_contents = thumb.execute_transforms(output_encoding=images.JPEG, quality=40) gcs_file = gcs.open(thumb_gcs_path, 'w', content_type='image/jpeg') gcs_file.write(thumb_contents) gcs_file.close() return (CLOUD_STORAGE_ROOT_URL + image_gcs_path, CLOUD_STORAGE_ROOT_URL + thumb_gcs_path)
def post(self, gallery_slug): action = self.request.get("action") if action == 'delete': photo_id = self.request.get("id") p = Photo.get_by_id(int(photo_id)) p.delete() return self._compose(gallery_slug, ['Delete Successful']) elif action == 'frontpage': photo_id = self.request.get("id") new_setting = self.request.get("frontpage") p = Photo.get_by_id(int(photo_id)) p.frontpage = (new_setting == 'include') p.put() return self._compose(gallery_slug, ['Edit Successful']) elif action == 'add': try: image = images.Image(self.request.get("img")) thumb = images.Image(self.request.get("img")) aspect_ratio = float(image.width) / float(image.height) # crop the image to make it square for the thumb if aspect_ratio > 1.0: left_x = float(image.width - image.height) / float( 2 * image.width) right_x = float(image.height + image.width) / float( 2 * image.width) thumb.crop(left_x, 0.0, right_x, 1.0) elif aspect_ratio < 1.0: top_y = float(image.height - image.width) / float( 2 * image.height) bottom_y = float(image.height + image.width) / float( 2 * image.height) thumb.crop(0.0, top_y, 1.0, bottom_y) thumb.resize(45, 45) image.resize(800, 600) #find gallery that we are adding to gallery = db.Query(Gallery).filter('slug =', gallery_slug).get() # is the photo to be displayed on the front page as well? fp = self.request.get("frontpage", False) if fp: fp = True # create and save the new photo new_photo = Photo( title=self.request.get("title"), image_data=db.Blob(image.execute_transforms()), thumb_data=db.Blob(thumb.execute_transforms()), extension='png', gallery=gallery, frontpage=fp) new_photo.put() #return self.response.out.write('<img src="%s_thumb.%s"></img>' % (new_photo.key().id(),new_photo.extension)) return self._compose(gallery_slug, ['Upload Successful']) except Exception, e: return self._compose(gallery_slug, ['Upload Failed', str(e)])
def post(self): self.checkSession(self.request.headers.get('Cookie')) self.insertMenu() id = int(self.request.uri.split('/')[-1]) photo = DBPhoto.get_by_id(id) albom_ppc = DBAlbum.get_by_id(int(photo.albumid)) if (self.Session['access'] >= 8 or self.Session['userid'] == int(albom_ppc.userid)): if self.request.get('pic'): 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( "Фотография не должна быть больше 1024x768 пикселей, но хотя бы одна сторона фотографии должна быть больше 400 пикселей" ) self.drawPage() return photo.image_big = db.Blob(image._image_data) photo.put() try: tags = DBPhotoTags.gql("where imageid = :imageid", imageid=id) if tags.count() == 0: 1 / 0 for tag in tags: tag.tags = self.request.get('tags') tag.put() except: tags = DBPhotoTags() tags.tags = self.request.get('tags') tags.imageid = id tags.put() self.insertContent("Изменено успешно!") self.drawPage() self.redirect("/album/%s" % str(albom_ppc.key().id()))
def post(self): img_from_request = self.request.get('img') image = images.Image(img_from_request) mime = "" extension = "" try: if image.format == images.JPEG: mime = "image/jpeg" extension = ".jpg" elif image.format == images.PNG: mime = "image/png" extension = ".png" except: self.response.set_status(500) self.response.write( TEMPLATE.render({'error': 'Unrecognized image format!'})) return id = generate_id() while ndb.Key(Images, id).get(): id = generate_id() write_retry_params = gcs.RetryParams(backoff_factor=1.1) gcs_file = gcs.open('/' + BUCKET_NAME + '/' + id, 'w', content_type=mime, retry_params=write_retry_params) gcs_file.write(img_from_request) gcs_file.close() thumb_img = images.Image(img_from_request) thumb_img.resize(width=492) thumbnail = thumb_img.execute_transforms(output_encoding=images.JPEG) img = Images(id=id, mime=mime, thumbnail=thumbnail) img_key = img.put() img_url = self.request.host_url + '/' + id + extension if self.request.headers.get('User-Agent').find('curl') >= 0: self.response.headers['Content-Type'] = 'text/plain' self.response.write(img_url + "\n") else: self.response.write( TEMPLATE.render({ 'img_id': img_key.id(), 'img_url': self.request.host_url + '/' + id + extension }))
def post(self): file_id = self.request.POST.get('file_id') key = ndb.Key('UploadedFile', file_id) ent = key.get() if ent.gs_path.endswith(IMAGE_EXTENSIONS): blob_key = blobstore.create_gs_key('/gs{}'.format(ent.gs_path)) serving_url = images.get_serving_url(blob_key, secure_url=True) data = blobstore.fetch_data(blob_key, 0, 50000) image = images.Image(image_data=data) ent.width = image.width ent.height = image.height else: serving_url = 'https://storage.googleapis.com{}'.format( ent.gs_path) ent.width = 0 ent.height = 0 ent.serving_url = serving_url ent.put() self.json_response({ 'file_id': file_id, 'gs_path': ent.gs_path, 'serving_url': serving_url, 'width': ent.width, 'height': ent.height, })
def adjustImgContent(self, content): #强制转换成JPEG img = images.Image(content) img.resize(width=(img.width-1), height=(img.height-1)) content = img.execute_transforms(output_encoding=images.JPEG) return content
def get(self, filename): # Check memcache first data = memcache.get(filename, MEMCACHE_NAMESPACE) if data is None: # Construct the full URL to the original image request_url = urlparse.urlparse(self.request.url) url = "%s://%s/screenshots/%s" % (request_url.scheme, request_url.netloc, filename) url = url.replace( '8080', '8081') # Because the dev server is single threaded logging.info(url) # Fetch the original image result = urlfetch.fetch(url) # Load it and resize it image = images.Image(image_data=result.content) image.resize(width=WIDTH) data = image.execute_transforms(output_encoding=images.PNG) # Put it in memcache memcache.set(filename, data, namespace=MEMCACHE_NAMESPACE) self.response.headers['Content-Type'] = 'image/png' self.response.headers['Cache-Control'] = 'public, max-age=86400' self.response.out.write(data)
def post(self): code = self.request.get('code',None) img = self.request.get('img',"") # simple antispam if sum(x in code.lower() for x in ('href=', 'url=', 'link=')) > 2: self.redirect("/error") return if code.strip(): hash = base64.b64encode(hashlib.sha1(code.strip()).digest()[:6], "-_") if not LogoProgram.all().filter('hash =', hash).get(): program = LogoProgram() program.code = code program.hash = hash if img: img = base64.b64decode(img) img = images.Image(img) img.resize(125, 125) program.img = img.execute_transforms() else: self.redirect("/error") return program.put() memcache.set("program: %s" % hash, program) memcache.delete("recent") else: hash = "" self.redirect("/%s" % hash)
def generateThumbnail(url): logging.info('generating thumbnail: %s' % url) thumbWidth, thumbHeight = THUMB_SIZE result = urlfetch.fetch(url) img = images.Image(result.content) w, h = img.width, img.height aspect = float(w) / h thumbAspect = float(thumbWidth) / thumbHeight if aspect > thumbAspect: # Too wide, so crop on the sides. normalizedCrop = (w - h * thumbAspect) / (2.0 * w) img.crop(normalizedCrop, 0., 1. - normalizedCrop, 1.) elif aspect < thumbAspect: # Too tall, so crop out the bottom. normalizedCrop = (h - w / thumbAspect) / h img.crop(0., 0., 1., 1. - normalizedCrop) img.resize(thumbWidth, thumbHeight) # Chose JPEG encoding because informal experiments showed it generated # the best size to quality ratio for thumbnail images. nimg = img.execute_transforms(output_encoding=images.JPEG) logging.info(' finished thumbnail: %s' % url) return nimg
def post(self): try: # json lib doesn't like trailing comma request = json.loads(re.sub(',[ \t\r\n]*\]', ']', self.request.body)) inputs, heights, widths = [], [], [] for element in request: # open file if fails then bad file image = images.Image(image_data=(open("img/"+element['filename'], "rb").read())) # check positive x = int(element['x']) if (x < 0): raise ValueError('X Offset is invalid: ' + str(x)) y = int(element['y']) if (y < 0): raise ValueError('Y Offset is invalid: ' + str(y)) widths.append(image.width + x) heights.append(image.height + y) inputs.append((image, x, y, 1.0, images.TOP_LEFT)) response = images.composite(inputs, max(widths), max(heights)) except IOError as err: self.response.headers['Content-Type'] = 'text/html' self.response.out.write("Image error: {0}".format(err)) except ValueError as err: self.response.headers['Content-Type'] = 'text/html' self.response.out.write("Request error: {0}".format(err) + " : " + request_json) else: self.response.headers['Content-Type'] = "image/png" self.response.out.write(response)
def write_blob(self, data, info): key = urllib.quote(info['type'].encode('utf-8'), '') +\ '/' + str(hash(data)) +\ '/' + urllib.quote(info['name'].encode('utf-8'), '') try: memcache.set(key, data, time=EXPIRATION_TIME) except: #Failed to add to memcache return (None, None) thumbnail_key = None if IMAGE_TYPES.match(info['type']): try: img = images.Image(image_data=data) img.resize( width=THUMB_MAX_WIDTH, height=THUMB_MAX_HEIGHT ) thumbnail_data = img.execute_transforms() thumbnail_key = key + THUMB_SUFFIX memcache.set( thumbnail_key, thumbnail_data, time=EXPIRATION_TIME ) except: #Failed to resize Image or add to memcache thumbnail_key = None return (key, thumbnail_key)
def get(self, pageid): articles = models.Article.all() articles.filter("slug =", pageid) article = articles.fetch(1) for art in article: rimages = [] rheights = [] for image in art.images: rimages.append(db.get(image)) img = images.Image(blob_key=str(db.get(image).file.key())) img.im_feeling_lucky() img.execute_transforms(output_encoding=images.JPEG, quality=1) rheights.append(float(img.height) / float(img.width)) art.rimages = rimages articles = models.Article.all().order('-pubdate').fetch(20) for sarticle in articles: sarticle.rimages = [db.get(image) for image in sarticle.images] self.generate('page.html', template_values={ 'articles': articles, 'article': article, 'rheights': rheights, 'pageid': pageid, })
def save_file(binary, filename, public=True, mime_type="application/octet-stream"): from google.appengine.api import files today = datetime.now().strftime("%Y_%m_%d_") filename = today + filename blob_file_name = files.blobstore.create( _blobinfo_uploaded_filename=filename) with files.open(blob_file_name, 'a') as f: f.write(binary) files.finalize(blob_file_name) blob_key = files.blobstore.get_blob_key(blob_file_name) try: # get serving url for images from google.appengine.api import images img = images.Image(binary) size = max(img.width, img.height) url = images.get_serving_url(blob_key, size=size) except: from settings import BLOB_SERVING_URL url = "%s/%s" % (BLOB_SERVING_URL, str(blob_key)) return url, str(blob_key)
def update_artist_photo(artist_key): artist = ndb.Key(urlsafe=artist_key).get() if not artist or not isinstance(artist, Artist): raise NotAllowedException() # Process the image uploaded_image = request.files.get('photo') if not uploaded_image: raise ImageException( description= 'Invalid image. Unable to get the image form the request in ' 'the correct format.') image = images.Image(uploaded_image.read()) if image.height < 1024 or image.width < 1024: raise ImageException( description= 'Invalid image size. The image uploaded was smaller then 1024 X 1024' ) # Scale to ensure the smallest dimension is 1024px image.resize(width=1024, height=1024, crop_to_fit=True) output_image = image.execute_transforms(output_encoding=images.PNG) photo_url = save_artist_photo('artist_{}.png'.format(artist_key), output_image) artist.photo = photo_url artist.is_active = True artist.put() return jsonify(artist=artist)
def post(self): #image_data – String of the source image data #jdata = json.loads(cgi.escape(self.request.body)) jdata = json.loads(self.request.body) corefname = jdata['requests'][0]['image']['corefn'] if corefname is None: corefname=DEFAULT_FILE_NAME photo=jdata['requests'][0]['image']['content'] photostr=base64.b64decode(photo) if photostr: img = images.Image(image_data=photostr) self.response.headers['Content-Type'] = 'text/html' self.response.out.write("Image information: WxH ") self.response.out.write(str(img.width) + "x" + str(img.height)) #bt = BucketTest(webapp2.RequestHandler) #bt.vision_into_bucket(str(img.width) + "x" + str(img.height)) self.vision_into_bucket(self.fmt_msg(str(img.width) + "x" + str(img.height)),'/'+corefname+'-raw') #self.vision_into_bucket(photo.encode('utf-8'),'/vision-demo-rawphoto') self.vision_into_bucket(base64.b64decode(photo),'/'+corefname+'-rawphoto.jpg') img.im_feeling_lucky() transformedphoto = img.execute_transforms(output_encoding=images.JPEG) self.vision_into_bucket(self.fmt_msg(str(img.width) + "x" + str(img.height)),'/'+corefname+'-transformed') self.vision_into_bucket(transformedphoto,'/'+corefname+'-transformedphoto.jpg') return # Either "id" wasn't provided, or there was no image with that ID # in the datastore. self.error(404)
def FetchAndSaveImage(self, url): """ Args: url: The url to fetch. Returns: The new blob key, or None if the fetch failed. """ logging.info('fetching %s' % url) try: image_response = urlfetch.fetch(url) except urlfetch.Error: return None if image_response.status_code != 200: logging.info('image fetch failed. %s -> %d' % (url, image_response.status_code)) return None img = images.Image(image_response.content) # shrink things if needed if img.width > self.RESIZE_WIDTH: img.resize(width=self.RESIZE_WIDTH) # we need at least one transform, so use I'm feeling lucky :) img.im_feeling_lucky() try: thumbnail = img.execute_transforms(output_encoding=images.PNG) except SystemError, e: # this fires on the dev server if it can't load the PIL module logging.info(e) return None
def thumbnail(id, width, height, ext): key = db.Key(id) picture = Picture.get(key) img = images.Image(picture.data) if width != '0': w = int(width) else: w = img.width if height != '0': h = int(height) else: h = img.height if img.height > h and h != 0: w = (int(width) * img.width) / img.height if img.width > w: h = (int(height) * img.height) / img.width thumb = images.resize(picture.data, width=w, height=h) response = make_response(thumb) response.headers['Content-Type'] = picture.content_type return response
def get_tile(tile_layer, tile, return_pil=False): tile_key = ( "/%s/tile/%s/%s/%s/%s" % (bucket_name, tile_layer.storage_key, tile["z"], tile["x"], tile["y"])) object_key = urllib.quote(tile_key) storage_api = gcs.storage_api._get_storage_api(None) status, header, content = \ yield storage_api.head_object_async(object_key) gcs.errors.check_status(status, [200, httplib.NOT_FOUND], object_key) if status == 200: logging.debug("found: %s", object_key) else: logging.debug("rendering: %s", object_key) tile_img = yield tile_layer.render_async(tile) tileb = io.BytesIO() tile_img.convert("RGBA").save(tileb, "png") yield upload_object_async(storage_api, object_key, tileb.getvalue(), "image/png") if return_pil: logging.info("loading: %s" % object_key) status, resp_headers, content = \ yield storage_api.get_object_async(object_key) gcs.errors.check_status(status, [200], object_key) raise ndb.Return(PIL.Image.open(io.BytesIO(content)).convert("RGBA")) else: logging.info("refing: %s" % tile_key) raise ndb.Return(images.Image(filename="/gs" + tile_key))
def read_gcs(self, filename): img_format = filename.split('.')[-1] gcs_filename = '/%s/%s' % (BUCKET_IMAGES, filename) try: #GCSのファイルチェックのみ使用--なければgcs.NotFoundError stat = gcs.stat(gcs_filename) #------------------------------------------------------ with gcs.open(gcs_filename) as f: img = images.Image(f.read()) img.resize(width=800, height=250) img.im_feeling_lucky() if img_format == 'jpg': return img.execute_transforms(output_encoding=images.JPEG) elif img_format == 'png': return img.execute_transforms(output_encoding=images.PNG) except gcs.NotFoundError: message = u'%s was not Found in gcs.' % filename return u'No image' except Exception as e: message = u'Blob read failed for %s, exception: %s. ' % (filename, str(e)) return u'No image' logging.error(message)
def set_thumbnail(photo): """Sets thumbnail data for a photo. Args: photo: the Photo object to set the thumbnail for """ image = images.Image(photo.image_data) if max(image.width, image.height) <= MAX_THUMBNAIL_DIMENSION: # Don't need a thumbnail, it's small enough already. return elif image.width > image.height: image.resize(MAX_THUMBNAIL_DIMENSION, image.height * MAX_THUMBNAIL_DIMENSION / image.width) else: image.resize(image.width * MAX_THUMBNAIL_DIMENSION / image.height, MAX_THUMBNAIL_DIMENSION) try: thumbnail_data = image.execute_transforms(output_encoding=images.PNG) except RequestTooLargeError: raise SizeTooLargeError() except Exception: # There are various images.Error exceptions that can be raised, as well # as e.g. IOError if the image is corrupt. raise PhotoError() photo.thumbnail_data = thumbnail_data photo.save()
def upload(image_data, *sizes): """ Uploads the given photo, returning a dict mapping from size name to a URL. """ now = int(time.time()) guid = uuid.uuid4() if not sizes: sizes = ['original'] # no cropping or resizing for size in sizes: # Choose image size, or default to original. max_width, max_height, crop_to_fit = SIZES.get(size, (0, 0, False)) # Resize image to fit in the given size, and re-encode as JPEG. img = images.Image(image_data) if max_width and max_height: img.resize(max_width, max_height, crop_to_fit=crop_to_fit) img.im_feeling_lucky() result_data = img.execute_transforms(output_encoding=images.JPEG) # Save the image to GCS. photo_id = "{}-{}-{}".format(now, guid, size) output_file = cloudstorage.open(filename="/{}/{}".format( GCS_BUCKET, photo_id), mode="w", content_type="image/jpg", options={"x-goog-acl": "public-read"}) output_file.write(result_data) output_file.close() return "{}-{}".format(now, guid)
def get(self, resource): resource = str(urllib.unquote(resource)) blob_info = blobstore.BlobInfo.get(resource) width = self.request.get('w') height = self.request.get('h') if not width: width = 700 else: width = int(width) if not height: height = 700 else: height = int(height) if blob_info: img = images.Image(blob_key=resource) img.resize(width=width, height=height) thumbnail = img.execute_transforms( output_encoding=images.JPEG) self.response.headers['Content-Type'] = 'image/jpeg' self.response.out.write(thumbnail) return # Either blob_key wasnt provided or there was no value with that ID # in the Blobstore self.error(404)
def get(self): user = users.get_current_user() if user: connected = True nik = "Welcome " + user.nickname() + "!" sign = None logout = users.create_logout_url("/") else: connected = False nik = "Please sign in" sign = users.create_login_url("/") logout = None all_images = Image.select_all() to_show = {} # resize all images content for i in all_images: img = images.Image(i.image_bin) img.resize(width=140, height=140, allow_stretch=True) # img.im_feeling_lucky() to_show[i.key] = img.execute_transforms(output_encoding=images.PNG) # if images.Image(all_images[i]).height > 40 or images.Image(all_images[i]).width > 40: # im = images.resize(images.Image(i.image_bin), width=40, height=40) template_values = { "connected": connected, "user": nik, "sign": sign, "logout": logout, "img": to_show } jinja = jinja2.get_jinja2(app=self.app) sleep(1) self.response.write( jinja.render_template("home.html", **template_values))
def get(self): path_file = open('normalized_2.txt') paths = path_file.readlines() path_file.close() image_data = [] offsets = [] alpha = 1.0 / len(paths) for parts in paths: file_name, x, y = parts.strip().split(' ') f = open(file_name) data = f.read() #images.resize(f.read(), width=800) w = images.Image(data).width data = images.resize(data, width=w / 4) f.close() image_data.append(data) offsets.append((-int(x) / 4, -int(y) / 4)) base_x, base_y = min(x[0] for x in offsets), min(x[1] for x in offsets) comp_tuples = [(data, x - base_x, y - base_y, alpha, images.TOP_LEFT) for (data, (x, y)) in zip(image_data, offsets)] comp_data = images.composite(comp_tuples, 640, 480) self.response.headers['Content-Type'] = 'image/jpg' self.response.out.write(comp_data)
def get(self): # read params blob_key = self.request.get("key") resize_w = self.request.get("w") resize_h = self.request.get("h") quality = int(self.request.get("q", 90)) crop_to_fit = True # get image and resize image = images.Image(blob_key=blob_key) if resize_w and resize_h: image.resize(width=int(resize_w), height=int(resize_h), crop_to_fit=crop_to_fit) elif resize_w: image.resize(width=int(resize_w)) elif resize_h: image.resize(height=int(resize_h)) else: image.resize(width=500) # generate and serve result = image.execute_transforms(output_encoding=images.JPEG, quality=quality) self.response.headers['Content-Type'] = 'image/jpeg' self.response.headers['Cache-Control'] = 'public, max-age=31536000' return self.response.out.write(result)