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
def post(self): n = Node() n.description = self.request.get('description') n.title = self.request.get('title') n.flag_is_end = self.request.get('flag_is_end') == 'true' n.node_id = n.obtainNewID() try: parent_node = Node.all().filter('node_id =', int(self.request.get('parent_id'))).get() except ValueError: n.parent_id = -1 n.tree_level = 1 n.tree_id = n.node_id else: n.parent_id = parent_node.node_id n.tree_level = parent_node.tree_level + 1 n.tree_id = parent_node.tree_id graph = self.request.get('graph') a = images.Image(self.request.get('graph')) if a.width > a.height: graph = images.crop(graph, 0.5-0.5*a.height/a.width, 0.0, 0.5+0.5*a.height/a.width, 1.0) else: graph = images.crop(graph, 0.0, 0.5-0.5*a.width/a.height, 1.0, 0.5+0.5*a.width/a.height) graph = images.resize(graph, 500, 500) n.graph = db.Blob(graph) n.put() n.graph_uri = '/userimg/' + str(n.key()) n.put() self.redirect('/context?node_id=%d' % n.node_id)
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 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 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 flickr_thumb(file,size): from google.appengine.api import images from zopeimage import getImageInfo type,width,height = getImageInfo(file) if width < height: file = images.resize(file,width=size) type,width,height = getImageInfo(file) cropoff = ((height - size)*.5)/height file = images.crop(file,top_y=cropoff,bottom_y=1.0 - cropoff,left_x=0.0,right_x=1.0) else: file = images.resize(file,height=size) type,width,height = getImageInfo(file) cropoff = ((width - size)*.5)/width file = images.crop(file,left_x=cropoff,right_x=1.0 - cropoff,top_y=0.0,bottom_y=1.0) return file
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 thumbnail(request,key=None): s = get_object_or_404(Storage,pk=key) read_path = '/%s/%s/%s'% (s.storage, s.bucket, s.path) image_data = read_gs(read_path) MIN_SIZE = 100 image = images.Image(image_data) width = image.width height = image.height if width>height: rate = width*1.0/height else: rate = height*1.0/width size = int(MIN_SIZE*rate+1) new_image = images.resize(image_data, width=size, height=size, output_encoding=images.PNG) image = images.Image(new_image) right_x = round(MIN_SIZE*1.0/image.width,5) if right_x>1: right_x = 1.0 else: left_x = (1- right_x)/2 right_x = right_x + left_x bottom_y = round(MIN_SIZE*1.0/image.height,5) if bottom_y >1: bottom_y = 1.0 else: top_y = (1-bottom_y)/2 bottom_y = bottom_y + top_y new_image = images.crop(new_image, left_x, top_y, right_x, bottom_y, output_encoding=images.PNG) return HttpResponse(new_image, s.mime)
def getEmojiImageDataFromSprite(e=None, code_points=None, show=False): # someshow PIL returns a pixelated image ''' box = getEmojiBoxInSprite(e,code_points) assert box region = EMOJI_SPRITE_IMAGE.crop(box) cropped_image = Image.new("RGBA", (EMOJI_SIZE, EMOJI_SIZE), (0, 0, 0, 0)) cropped_image.paste(region, (0, 0)) imgData = StringIO.StringIO() cropped_image.save(imgData, format="PNG", quality=100) if show: cropped_image.show() return imgData.getvalue() ''' from google.appengine.api import images box = getEmojiBoxInSprite(e, code_points) assert box x_left = float(box[0]) / EMOJI_SPRITE_WIDTH y_top = float(box[1]) / EMOJI_SPRITE_HEIGHT x_right = float(box[2]) / EMOJI_SPRITE_WIDTH y_bottom = float(box[3]) / EMOJI_SPRITE_HEIGHT sticker_data = images.crop(image_data=SPRITE_IMG_STR, left_x=x_left, top_y=y_top, right_x=x_right, bottom_y=y_bottom, output_encoding=images.PNG) return sticker_data
def add_blog_node(addr,img,title,description,link): if img == None: return None newNode = ImageContent() if users.get_current_user(): newNode.owner = users.get_current_user() if img: newNode.img_src = db.Blob(img) tmpImg = images.Image(img) # if tmpImg.width >= tmpImg.height: # addImg = images.resize(tmpImg._image_data,0,240) # else: addImg = images.resize(tmpImg._image_data,240,0) newNode.instax_src = db.Blob(addImg) addImg = images.crop(addImg,0.0,0.0,80.0/images.Image(addImg).width,80.0/images.Image(addImg).height) newNode.thumb = db.Blob(addImg); newNode.ip_addr = addr newNode.iszombie = False newNode.put(); return newNode
def pyamf_add_image_node(fbuser,addr,img): if img == None: return None newNode = ImageContent() if fbuser: newNode.fb_owner = fbuser if img: newNode.img_src = db.Blob(img) tmpImg = images.Image(img) # if tmpImg.width >= tmpImg.height: # addImg = images.resize(tmpImg._image_data,0,240) # else: addImg = images.resize(tmpImg._image_data,240,0) newNode.instax_src = db.Blob(addImg) addImg = images.crop(addImg,0.0,0.0,80.0/images.Image(addImg).width,80.0/images.Image(addImg).height) newNode.thumb = db.Blob(addImg); newNode.ip_addr = addr newNode.iszombie = False newNode.put(); return newNode
def makeThumb( im, x0, y0 ): #makes a thumbnail. not used currently. trys to balance cropping with scaling so that image fill is decent in 100px by 1--px square im2 = images.Image(im) w = im2.width h = im2.height ratio = (y0 * 1.0) / x0 iratio = (h * 1.0) / w rratio = iratio / ratio if rratio > 2: nh = w * ratio * 2 d = ((h - nh) * .5) / h im = images.crop(im, 0.0, d, 1.0, 1. - d) elif rratio < .5: nw = h / ratio * 2 d = ((w - nw) * .5) / w im = images.crop(im, d, 0.0, 1.0 - d, 1.0) return images.resize(im, x0, y0, 1)
def flickr_thumb(file,size): """ returns squared cropped thumbnail """ width,height = getImageInfo(file) if width < height: file = images.resize(file,width=size) width,height = getImageInfo(file) cropoff = ((height - size)*.5)/height file = images.crop(file,top_y=cropoff, bottom_y=1.0 - cropoff,left_x=0.0,right_x=1.0) else: file = images.resize(file,height=size) width,height = getImageInfo(file) cropoff = ((width - size)*.5)/width file = images.crop(file,left_x=cropoff, right_x=1.0 - cropoff,top_y=0.0,bottom_y=1.0) file = images.im_feeling_lucky(file, images.JPEG) return file
def getEmojiStickerDataFromUrl(e): png_data = getEmojiPngDataFromUrl(e) assert png_data from google.appengine.api import images sticker_data = images.crop(image_data=png_data, left_x=0.0, top_y=0.0, right_x=1.0, bottom_y=1.0, output_encoding=images.WEBP) return sticker_data
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))
def zoom_old(self): tile_x = x / (2** (z - ref_zoom)) tile_y = y / (2** (z - ref_zoom)) imgname = "%s/%s/%d/%d_%d.png" % (typename,mapname,ref_zoom,tile_x,tile_y) imgstream = self.download( "http://" + site + prefix + imgname ) width = height = 256 / (2** (z - ref_zoom)) xoffset = width * (x % (2** (z - ref_zoom))) yoffset = height * (y % (2** (z - ref_zoom))) outpic = images.crop( imgstream, float(xoffset)/incols, float(yoffset)/inrows, float(xoffset + width)/incols, float(yoffset + height)/inrows ) outpic = images.resize( outpic, outcols,outrows ) self.response.headers['Content-Type'] = "image/png"; self.response.out.write( outpic ) return
def create_image_blob(img): newBlob = ImageBlob() logging.debug('create_image_blob') newBlob.img_src = db.Blob(img) tmpImg = images.Image(img) logging.debug('resize') addImg = images.resize(tmpImg._image_data,240,0) newBlob.instax_src = db.Blob(addImg) logging.debug('crop') addImg = images.crop(addImg,0.0,0.0,80.0/images.Image(addImg).width,80.0/images.Image(addImg).height) newBlob.thumb = db.Blob(addImg); newBlob.put() return newBlob
def cropComposite(self): #crop to desired pixel size, centered on the bounds. left_x = float( (self.cX-self.size[0]/2-(self.tileCoords[0]*256))/self.pixWidth) top_y = float( (self.cY-self.size[1]/2-(self.tileCoords[3]*256))/self.pixHeight) right_x = float( 1-(((self.tileCoords[2]+1)*256)-(self.cX+self.size[0]/2))/ self.pixWidth) bottom_y = float( 1-(((self.tileCoords[1]+1)*256)-(self.cY+self.size[1]/2))/ self.pixHeight) self.image = images.crop(self.image, left_x, top_y, right_x, bottom_y)
def post(self): #check login if not users.get_current_user(): self.redirect(users.create_login_url('/')) user = users.get_current_user() query = db.GqlQuery("SELECT * FROM Image WHERE user = :1", user) saved_image = query.get() action = self.request.get("action") if saved_image and action: if action == "resize": width = self.request.get("width") height = self.request.get("height") if width and height: img = images.resize(saved_image.data, int(width), int(height), saved_image.output_encoding) elif action == "rotate": degrees = self.request.get("degrees") if degrees: img = images.rotate(saved_image.data, int(degrees), saved_image.output_encoding) elif action == "im_feeling_lucky": img = images.im_feeling_lucky(saved_image.data, saved_image.output_encoding) elif action == "crop": left_x = self.request.get("left_x") top_y = self.request.get("top_y") right_x = self.request.get("right_x") bottom_y = self.request.get("bottom_y") if left_x and top_y and right_x and bottom_y: img = images.crop(saved_image.data, float(left_x), float(top_y), float(right_x), float(bottom_y), saved_image.output_encoding) if img: # save new settings output_encoding = saved_image.output_encoding content_type, width, height = getImageInfo(img) # delete previous entity for image in query: db.delete(image) image = Image() image.user = user image.data = db.Blob(img) image.output_encoding = output_encoding image.content_type = content_type image.width = width image.height = height image.put()
def post(self): req = self.request errorUrl = '/?error=true' # is targetUrl a valid image? leadImgFetch = urlfetch.fetch(req.get("targetUrl")) if leadImgFetch.status_code != 200: self.redirect(errorUrl) return try: # verify it's an image, and convert to PNG lead_img = images.crop(leadImgFetch.content, 0.0, 0.0, 1.0, 1.0, output_encoding=images.PNG) except: # not an image self.redirect(errorUrl) return # is feedUrl a valid feed? feedUrlData = urlfetch.fetch(req.get("feedUrl")) if feedUrlData.status_code != 200: self.redirect(errorUrl) return # save the job to the database try: feedfile = StringIO(feedUrlData.content) feedimages = picasafeed.getthumbnailsfromfile(feedfile) assert len(feedimages) > 0 except: self.redirect(errorUrl) return content_type, width, height = getImageInfo(lead_img) job = Job(user=users.get_current_user(), lead_img_url=db.Link(req.get("targetUrl")), lead_img=lead_img, lead_img_size=[width, height], feed_urls=feedimages, uncreated_thumb_indexes=range(len(feedimages))) job.put() self.redirect('/mosaic/%s/build' % job.key().id())
def getEmojiStickerFromSprite(e): from google.appengine.api import images box = getEmojiBoxInSprite(e) assert box x_left = float(box[0]) / EMOJI_SPRITE_WIDTH y_top = float(box[1]) / EMOJI_SPRITE_HEIGHT x_right = float(box[2]) / EMOJI_SPRITE_WIDTH y_bottom = float(box[3]) / EMOJI_SPRITE_HEIGHT sticker_data = images.crop(image_data=SPRITE_IMG_STR, left_x=x_left, top_y=y_top, right_x=x_right, bottom_y=y_bottom, output_encoding=images.WEBP) return sticker_data
def post(self): if super(AdminAlbumAdd, self).get(): self.response.headers['Content-Type'] = "text/html" if int(self.request.get("isphoto"))==1: try: photo = DBPhoto() photo.albumid = int(self.request.get("albumid")) photo.tags = "" secret = str(hashlib.md5(str(random.random())).hexdigest()) photo.comment = "secret" + secret image = images.Image(self.request.get('pic')) if (image.width < 400 and image.height < 400) or image.width > 1024 or image.height > 768: self.response.out.write("size") return 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.put() photos = DBPhoto.gql("where comment = :cmt", cmt = "secret" + secret) id = str(photos[0].key().id()) edphoto = DBPhoto.get_by_id(int(id)) edphoto.comment = "none" edphoto.image_small = db.Blob(image_cropped) edphoto.image_big = db.Blob(image._image_data) edphoto.put() self.response.out.write(id) except: self.response.out.write("size") else: if int(self.request.get("deletephoto"))==1: try: photo = DBPhoto.get_by_id(int(self.request.get("photoid"))) db.delete(photo) self.response.out.write("deleted") except: self.response.out.write("not deleted") else: try: album = DBAlbum.get_by_id(int(self.request.get("albumid"))) album.objectid = int(self.request.get("objectid")) object = DBGalleryObject.get_by_id(int(self.request.get("objectid"))) album.userid = int(object.userid) album.name = self.request.get("name") album.put() self.response.out.write("added") except: self.response.out.write("not added")
def post(self): photo = self.request.get('img') image_type = self.request.get('image_type') print(image_type) request_left_x = self.request.get('left_x') request_top_y = self.request.get('top_y') request_right_x = self.request.get('right_x') request_bottom_y = self.request.get('bottom_y') encoding_type = images.JPEG if image_type == "PNG": encoding_type = images.PNG print(str(encoding_type)) photo = images.crop(photo,left_x=float(request_left_x),top_y=float(request_top_y),right_x=float(request_right_x),bottom_y=float(request_bottom_y),quality=100,output_encoding=encoding_type) if self.request.get('enhance_color') == "true": photo = images.im_feeling_lucky(photo,output_encoding=encoding_type,quality=100) print("Yes enhancing") #photo = images.execute_transforms(photo,output_encoding=images.JPEG,quality=100) self.response.headers['Content-Type'] = 'image/'+str(image_type).lower() self.response.out.write(photo)
def _create_blocks(self, blob): """ Breaks _master down into blobs. Blobs are squares of BLOCKSIZE pixels to a side. If the master blob must factor into BLOCKSIZE""" blobs = [] for (x_offset_blocks, y_offset_blocks) in product(xrange(0, self._output_width / BLOCKSIZE), xrange(0, self._output_height / BLOCKSIZE)): x_offset_pixels = x_offset_blocks * BLOCKSIZE y_offset_pixels = y_offset_blocks * BLOCKSIZE x_offset_fraction = float(x_offset_pixels) / self._output_width y_offset_fraction = float(y_offset_pixels) / self._output_height x_right_fraction = x_offset_fraction + (BLOCKSIZE / float(self._output_width)) y_bottom_fraction = y_offset_fraction + (BLOCKSIZE / float(self._output_height)) # logging.debug("x pixels: {}, width: {}, x fraction: {}, right fraction: {}".format(x_offset_pixels, self._output_width, x_offset_fraction, x_right_fraction)) # logging.debug("y piyels: {}, height: {}, y fraction: {}, bottom fraction: {}".format(y_offset_pixels, self._output_height, y_offset_fraction, y_bottom_fraction)) blobs.append( ( images.crop(blob, x_offset_fraction, y_offset_fraction, x_right_fraction, y_bottom_fraction), x_offset_pixels, y_offset_pixels ) ) return blobs
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 generate_thumbnail(image_data, min_source_height, max_source_height, min_source_width, max_source_width, content_type, width, height, overlay_path, valign, top_crop_pct=None, bottom_crop_pct=None, left_crop_pct=None, right_crop_pct=None, crop_x=None, crop_y=None, post_crop_uniform_scale_pct=None): """ Generate a thumbnail and return the image data as a binary string. If unable to create the thumbnail, will return None. :min_source_height: If specified, a thumbnail will only be generated if the incoming image is at least this high. :min_source_width: If specified, a thumbnail will only be generated if the incoming image is at least this wide. :max_source_height: If specified, a thumbnail will only be generated if the incoming image is less than this many pixels high. :max_source_width: If specified, a thumbnail will only be generated if the incoming image is less than this many pixels wide. :image_data: Image data, as a bytestring :content_type: The MIME content type of the image. :width: Width of the thumbnail :height: Height of the thumbnail :overlay_path: Full path to an image file to overlay on top of the image data, or None to not use an overlay. :valign: A string, one of: "top" "bottom" "middle" describing how the image should be aligned along the Y-axis when cropping. :top_crop_pct: :bottom_crop_pct: Optional. Floats indicating how much from the top and bottom of the original image to crop in before rescaling. Numbers between 0 and 1.0 incl. :crop_x: :crop_y: Optional. If specified with width and height, will simply cut out a rectangle of the incoming image which is width x height and has its upper-left corner pegged to (crop_x, cropy_y). NOTE: For crop_x and crop_y to work, the following other options must be None: valign, top_crop_pct, bottom_crop_pct :post_crop_uniform_scale_pct: If not None, will scale image after cropping by the indicated percent. Should be None or a float between 0.0 and 1.0 """ # figure out the width/height of the image from the datastore # img = images.Image(image_data=image_data) # img.crop(left_x=0.25, top_y=0.25, right_x=0.25, bottom_y=0.25) # img.resize(width=width, height=height) # logging.info('(b) w=%i, h=%i' % (img.width, img.height)) # output = img.execute_transforms(output_encoding=img.format) image = images.Image(image_data) if min_source_height is not None and image.height < min_source_height: return None if max_source_height is not None and image.height > max_source_height: return None if min_source_width is not None and image.width < min_source_width: return None if max_source_width is not None and image.width > max_source_width: return None if content_type == 'image/png': output_encoding = images.PNG else: output_encoding = images.JPEG if crop_x is not None and crop_y is not None and valign is None and top_crop_pct is None and bottom_crop_pct is None and (image.width >= crop_x + width) and (image.height >= crop_y + height): fw = float(image.width) fh = float(image.height) try: output = images.crop(image_data, float(crop_x) / fw, float(crop_y) / fh, float(crop_x + width) / fw, float(crop_y + height) / fh, output_encoding=output_encoding) except: output = image_data else: if width > image.width and height > image.height: output = image_data # # this would result in scaling the image UP, that's no good # if image.width > image.height: # width = image.width # else: # height = image.height # # output = images.resize(image_data, width, height, output_encoding) else: output = rescale(image, width, height, halign='middle', valign=valign, top_crop_pct=top_crop_pct, bottom_crop_pct=bottom_crop_pct, left_crop_pct=left_crop_pct, right_crop_pct=right_crop_pct) if post_crop_uniform_scale_pct is not None: output = images.resize(output, width=int(width * post_crop_uniform_scale_pct), output_encoding=output_encoding) if overlay_path is not None: # read the overlay into memory overlay_data = open(overlay_path,'r').read() # composite the overlay onto the rescaled output if content_type == 'image/png': output_encoding = images.PNG else: output_encoding = images.JPEG output = images.composite( inputs=[ (output,0,0,1.0,images.CENTER_CENTER), (overlay_data,0,0,1.0,images.CENTER_CENTER), ], width=width, height=height, output_encoding=output_encoding ) return output
def generate_thumbnail(image_data, min_source_height, max_source_height, min_source_width, max_source_width, content_type, width, height, overlay_path, valign, top_crop_pct=None, bottom_crop_pct=None, left_crop_pct=None, right_crop_pct=None, crop_x=None, crop_y=None, post_crop_uniform_scale_pct=None): """ Generate a thumbnail and return the image data as a binary string. If unable to create the thumbnail, will return None. :min_source_height: If specified, a thumbnail will only be generated if the incoming image is at least this high. :min_source_width: If specified, a thumbnail will only be generated if the incoming image is at least this wide. :max_source_height: If specified, a thumbnail will only be generated if the incoming image is less than this many pixels high. :max_source_width: If specified, a thumbnail will only be generated if the incoming image is less than this many pixels wide. :image_data: Image data, as a bytestring :content_type: The MIME content type of the image. :width: Width of the thumbnail :height: Height of the thumbnail :overlay_path: Full path to an image file to overlay on top of the image data, or None to not use an overlay. :valign: A string, one of: "top" "bottom" "middle" describing how the image should be aligned along the Y-axis when cropping. :top_crop_pct: :bottom_crop_pct: Optional. Floats indicating how much from the top and bottom of the original image to crop in before rescaling. Numbers between 0 and 1.0 incl. :crop_x: :crop_y: Optional. If specified with width and height, will simply cut out a rectangle of the incoming image which is width x height and has its upper-left corner pegged to (crop_x, cropy_y). NOTE: For crop_x and crop_y to work, the following other options must be None: valign, top_crop_pct, bottom_crop_pct :post_crop_uniform_scale_pct: If not None, will scale image after cropping by the indicated percent. Should be None or a float between 0.0 and 1.0 """ # figure out the width/height of the image from the datastore # img = images.Image(image_data=image_data) # img.crop(left_x=0.25, top_y=0.25, right_x=0.25, bottom_y=0.25) # img.resize(width=width, height=height) # logging.info('(b) w=%i, h=%i' % (img.width, img.height)) # output = img.execute_transforms(output_encoding=img.format) image = images.Image(image_data) if min_source_height is not None and image.height < min_source_height: return None if max_source_height is not None and image.height > max_source_height: return None if min_source_width is not None and image.width < min_source_width: return None if max_source_width is not None and image.width > max_source_width: return None if content_type == 'image/png': output_encoding = images.PNG else: output_encoding = images.JPEG if crop_x is not None and crop_y is not None and valign is None and top_crop_pct is None and bottom_crop_pct is None and ( image.width >= crop_x + width) and (image.height >= crop_y + height): fw = float(image.width) fh = float(image.height) try: output = images.crop(image_data, float(crop_x) / fw, float(crop_y) / fh, float(crop_x + width) / fw, float(crop_y + height) / fh, output_encoding=output_encoding) except: output = image_data else: if width > image.width and height > image.height: output = image_data # # this would result in scaling the image UP, that's no good # if image.width > image.height: # width = image.width # else: # height = image.height # # output = images.resize(image_data, width, height, output_encoding) else: output = rescale(image, width, height, halign='middle', valign=valign, top_crop_pct=top_crop_pct, bottom_crop_pct=bottom_crop_pct, left_crop_pct=left_crop_pct, right_crop_pct=right_crop_pct) if post_crop_uniform_scale_pct is not None: output = images.resize(output, width=int(width * post_crop_uniform_scale_pct), output_encoding=output_encoding) if overlay_path is not None: # read the overlay into memory overlay_data = open(overlay_path, 'r').read() # composite the overlay onto the rescaled output if content_type == 'image/png': output_encoding = images.PNG else: output_encoding = images.JPEG output = images.composite(inputs=[ (output, 0, 0, 1.0, images.CENTER_CENTER), (overlay_data, 0, 0, 1.0, images.CENTER_CENTER), ], width=width, height=height, output_encoding=output_encoding) return output
def post(self): userId = self.user_id root = ET.fromstring(self.request.get('data')) mode = self.request.get('mode',default_value="gallery") fsbid = self.request.get('fsbid',default_value="") remove_namespace(root,"http://www.w3.org/1999/xhtml") imgId = '' family = 'Impact' size = '34' bid='' color = '#FFFFFF' style = 'normal' weight = 'normal' shadowcolor = "black" top = 20 left = 20 textlayers = [] tags = [] objects = root if 1 == 1: selectionwidth = int(float(objects.get('width'))) selectionheight = int(float(objects.get('height'))) rows = 1 columns = 1 totalwidth = selectionwidth totalheight = selectionheight panelwidth = selectionwidth panelheight = selectionheight otype = 'normal' if objects.get('type') == "conversation": totalwidth = selectionwidth totalheight = selectionheight rows = objects.get('rows') columns = objects.get('columns') panelwidth = selectionwidth/int(columns) panelheight = selectionheight/int(rows) otype = 'conv' con_back_layer = Image.new('RGBA', (totalwidth,totalheight), (204, 204, 204, 100)) output = StringIO.StringIO() con_back_layer.save(output, format="png") con_back_layer = output.getvalue() output.close() woffset = 0 hofsset = 0 rrindex = 0 rcindex = 0 textindex = 0 toptexts = [] bottomtexts = [] for texts in objects: if texts.tag == "imagebase": textindex = textindex + 1 imgId = texts.get('id') imgwidth = texts.get('width') imgheight = texts.get('height') # read background image meme_query = MemeDb.query(MemeDb.myid == imgId) #meme_query = MemeDb.query(ancestor=meme_dbkey(MEME_DB_NAME)).order(-MemeDb.date) memes = meme_query.fetch(1) for meme in memes: blob_reader = blobstore.BlobReader(meme.resid) background = images.Image(blob_reader.read()) tags = meme.tags background.resize(width=int(imgwidth), height=int(imgheight)) background.im_feeling_lucky() thumbnail = background.execute_transforms(output_encoding=images.JPEG) if otype == 'normal': back_layer = Image.new('RGBA', (totalwidth,totalheight), (204, 204, 204, 100)) output = StringIO.StringIO() back_layer.save(output, format="png") back_layer = output.getvalue() output.close() #merge merged = images.composite([(back_layer, 0,0, 1.0, images.TOP_LEFT), (thumbnail, (totalwidth-int(imgwidth))/2, (totalheight - int(imgheight))/2, 1.0, images.TOP_LEFT)], totalwidth, totalheight) else: back_layer = Image.new('RGBA', (panelwidth,panelheight), (204, 204, 204, 100)) output = StringIO.StringIO() back_layer.save(output, format="png") back_layer = output.getvalue() output.close() #merge merged = images.composite([(back_layer, 0,0, 1.0, images.TOP_LEFT), (thumbnail, (panelwidth-int(imgwidth))/2, (panelheight - int(imgheight))/2, 1.0, images.TOP_LEFT)], panelwidth, panelheight) if rrindex == int(columns): rrindex = 0 rcindex = rcindex + 1 woffset = rrindex*panelwidth if rcindex == int(rows): rcindex = 0 hoffset = rcindex*panelheight logging.info("%stheju%s" %(rrindex,rcindex)) con_back_layer = images.composite([(con_back_layer, 0,0, 1.0, images.TOP_LEFT), (merged, woffset,hoffset, 1.0, images.TOP_LEFT)], totalwidth, totalheight) merged = con_back_layer rrindex = rrindex + 1 for child in texts: if child.tag == "toptext": toptexts.append(child.get('text')) if child.tag == "bottomtext": bottomtexts.append(child.get('text')) textindex = 1 for bottomtext in bottomtexts: top = panelheight*(textindex - 1) + panelheight - 60 left = 20 textindex = textindex + 1 logging.info("%stoptext" %top) width = panelwidth height = 50 textVal = bottomtext text_img = Image.new('RGBA', (int(width),int(height)), (0, 0, 0, 0)) draw = ImageDraw.Draw(text_img) font=ImageFont.truetype(GetFontName(family,style,weight),int(size)) apString = '' lines = [] for x in range(0, len(textVal)): tempString = apString apString = apString + '%s' %textVal[x] width1, height1 = font.getsize(apString) if width1 >= int(width): lines.append(tempString) apString = '%s' %textVal[x] if apString != '': lines.append(apString) #lines = textwrap.wrap(textVal, width = 10) y_text = 0 for line in lines: font=ImageFont.truetype(GetFontName(family,style,weight),int(size)) width1, height1 = font.getsize(line) offset = (int(width) - int(width1))/2 draw.text((-2+offset, y_text-2), line, font=font, fill=shadowcolor) draw.text((+2+offset, y_text-2), line, font=font, fill=shadowcolor) draw.text((-2+offset, y_text+2), line, font=font, fill=shadowcolor) draw.text((+2+offset, y_text+2), line, font=font, fill=shadowcolor) draw.text((0+offset, y_text), line, font = font,fill=color) y_text += height1 # no write access on GAE output = StringIO.StringIO() text_img.save(output, format="png") text_layer = output.getvalue() output.close() textlayers.append(text_layer) merged = images.composite([(merged, 0,0, 1.0, images.TOP_LEFT), (text_layer, int(float(left)),int(float(top)), 1.0, images.TOP_LEFT)], totalwidth, totalheight) textindex = 1 for toptext in toptexts: top = 20 + panelheight*(textindex - 1) left = 20 textindex = textindex + 1 logging.info("%stoptext" %top) width = panelwidth height = 50 textVal = toptext text_img = Image.new('RGBA', (int(width),int(height)), (0, 0, 0, 0)) draw = ImageDraw.Draw(text_img) font=ImageFont.truetype(GetFontName(family,style,weight),int(size)) apString = '' lines = [] for x in range(0, len(textVal)): tempString = apString apString = apString + '%s' %textVal[x] width1, height1 = font.getsize(apString) if width1 >= int(width): lines.append(tempString) apString = '%s' %textVal[x] if apString != '': lines.append(apString) #lines = textwrap.wrap(textVal, width = 10) y_text = 0 for line in lines: font=ImageFont.truetype(GetFontName(family,style,weight),int(size)) width1, height1 = font.getsize(line) offset = (int(width) - int(width1))/2 draw.text((-2+offset, y_text-2), line, font=font, fill=shadowcolor) draw.text((+2+offset, y_text-2), line, font=font, fill=shadowcolor) draw.text((-2+offset, y_text+2), line, font=font, fill=shadowcolor) draw.text((+2+offset, y_text+2), line, font=font, fill=shadowcolor) draw.text((0+offset, y_text), line, font = font,fill=color) y_text += height1 # no write access on GAE output = StringIO.StringIO() text_img.save(output, format="png") text_layer = output.getvalue() output.close() textlayers.append(text_layer) merged = images.composite([(merged, 0,0, 1.0, images.TOP_LEFT), (text_layer, int(float(left)),int(float(top)), 1.0, images.TOP_LEFT)], totalwidth, totalheight) merged = images.crop(merged,float(0),float(0), 1.0,1.0) # save file_name = files.blobstore.create(mime_type='image/png') with files.open(file_name, 'a') as f: f.write(merged) files.finalize(file_name) blob_key = files.blobstore.get_blob_key(file_name) #memeid = SaveFinalMeme(userId,blob_key,tags,bid,mode) memeid = SaveMobileFinalMeme(userId,blob_key,tags,fsbid,mode) oauth_access_token = secrets.GetAccessToken() graph = GraphAPI(oauth_access_token) # Get my latest posts # Post a photo of a parrot if mode == "gallery": if smashedmisc.is_production () == True: urlfetch.set_default_fetch_deadline(45) postid = graph.post( path = '/431907476935431/photos', message = 'Created from smashed.in. Go to www.smashed.in/oh/record and record what you heard!', url = 'http://www.smashed.in/res/download/%s' % blob_key ) #logging.info('theju/%s' % postid['id']) UpdateFacebookId (memeid,postid['id']) self.response.write ('%s' % blob_key)
name_img = chart_img("http://chart.apis.google.com/chart?" "chst=d_text_outline&chld=000000|13|l|ffffff|_|%s" "&chf=bg,s,ffffff" % quote(name.encode('utf-8'))) # Start generating the actual tweetshot lines = len(line_imgs) width, height = t_width + 2 * MARGIN, t_height + 2 * MARGIN + (lines - 1) * LINE # Damn the rounded corners; need to seriously slice and re-compose px3 = 3. / t_width top1 = images.crop(tmpl_data, px3, 0., 1. - px3, PADDINGF / t_height) top2 = images.crop(tmpl_data, 0., 3. / t_height, 1., PADDINGF / t_height) line_bg = images.crop(tmpl_data, 0., PADDINGF / t_height, 1., (PADDINGF + LINE) / t_height) bottom1 = images.crop(tmpl_data, px3, (PADDINGF + LINE) / t_height, 1 - px3, 1.)
def create(cls, blob_key=None, blob_info=None, data=None, filename=None, url=None, mime_type=None, **kwargs): """ Create an ``Image``. Use this class method rather than creating an image with the constructor. You must provide one of the following parameters ``blob_info``, ``data``, or ``url`` to specify the image data to use. :param blob_key: The `Blobstore`_ data to use as the image data. If this parameter is not ``None``, all other parameters will be ignored as they are not needed (Only use with `NdbImage`). :param blob_info: The `Blobstore`_ data to use as the image data. If this parameter is not ``None``, all other parameters will be ignored as they are not needed (Do not use with `NdbImage`). :param data: The image data that should be put in the `Blobstore`_ and used as the image data. :param filename: The filename of the image data. If not provided, the filename will be guessed from the URL or, if there is no URL, it will be set to the stringified `Key`_ of the image entity. :param url: The URL to fetch the image data from and then place in the `Blobstore`_ to be used as the image data. :param mime_type: The `mime type`_ to use for the `Blobstore`_ image data. If ``None``, it will attempt to guess the mime type from the url fetch response headers or the filename. :param parent: Inherited from `Model`_. The `Model`_ instance or `Key`_ instance for the entity that is the new image's parent. :param key_name: Inherited from `Model`_. The name for the new entity. The name becomes part of the primary key. :param key: Inherited from `Model`_. The explicit `Key`_ instance for the new entity. Cannot be used with ``key_name`` or ``parent``. If ``None``, falls back on the behavior for ``key_name`` and ``parent``. :param kwargs: Initial values for the instance's properties, as keyword arguments. Useful if subclassing. :return: An instance of the ``Image`` class. """ if filename is not None: filename = filename.encode('ascii', 'ignore') if url is not None: url = url.encode('ascii', 'ignore') if blob_info is not None: if issubclass(cls, Image): kwargs['blob_info'] = blob_info else: kwargs['blob_key'] = blob_info.key() return cls.create_new_entity(**kwargs) if blob_key is not None: if issubclass(cls, NdbImage): kwargs['blob_key'] = blob_key else: kwargs['blob_info'] = blob_key return cls.create_new_entity(**kwargs) if data is None: if url is not None: response = urlfetch.fetch(url) data = response.content mime_type = mime_type or response.headers.get('Content-Type', None) if filename is None: path = urlparse.urlsplit(url)[2] filename = path[path.rfind('/')+1:] if data is None: raise db.Error("No image data") image = cls.create_new_entity(source_url=url, **kwargs) filename = filename or image.model_key_string mime_type = mime_type or mimetypes.guess_type(filename)[0] or 'application/octet-stream' if mime_type not in ImageConfig.get_config(_cache=True).VALID_MIME_TYPES: message = "The image mime type (%s) isn't valid" % mime_type logging.warning(message) image.delete() raise images.BadImageError(message) gae_image = images.Image(data) format = gae_image.format new_format = None if mime_type == 'image/jpeg' and format != images.JPEG: new_format = images.JPEG if mime_type == 'image/png' and format != images.PNG: new_format = images.PNG if new_format is not None: data = images.crop(data, 0.0, 0.0, 1.0, 1.0, output_encoding=new_format, quality=100) try: blob_file_name = files.blobstore.create(mime_type=mime_type, _blobinfo_uploaded_filename=filename) with files.open(blob_file_name, 'a') as f: f.write(data) files.finalize(blob_file_name) image.blob_key = files.blobstore.get_blob_key(blob_file_name) except AssertionError: # Needed to create an Image from url or image_data in a unittest. # Hopefully we can remove this when this bug is fixed: # http://code.google.com/p/googleappengine/issues/detail?id=5301 global TESTBED_INSTANCE _ = TESTBED_INSTANCE.get_stub('blobstore').CreateBlob(filename, data) image.blob_key = blobstore.BlobKey(filename) image.put() return image
def create(cls, blob_key=None, blob_info=None, data=None, filename=None, url=None, mime_type=None, **kwargs): """ Create an ``Image``. Use this class method rather than creating an image with the constructor. You must provide one of the following parameters ``blob_info``, ``data``, or ``url`` to specify the image data to use. :param blob_key: The `Blobstore`_ data to use as the image data. If this parameter is not ``None``, all other parameters will be ignored as they are not needed (Only use with `NdbImage`). :param blob_info: The `Blobstore`_ data to use as the image data. If this parameter is not ``None``, all other parameters will be ignored as they are not needed (Do not use with `NdbImage`). :param data: The image data that should be put in the `Blobstore`_ and used as the image data. :param filename: The filename of the image data. If not provided, the filename will be guessed from the URL or, if there is no URL, it will be set to the stringified `Key`_ of the image entity. :param url: The URL to fetch the image data from and then place in the `Blobstore`_ to be used as the image data. :param mime_type: The `mime type`_ to use for the `Blobstore`_ image data. If ``None``, it will attempt to guess the mime type from the url fetch response headers or the filename. :param parent: Inherited from `Model`_. The `Model`_ instance or `Key`_ instance for the entity that is the new image's parent. :param key_name: Inherited from `Model`_. The name for the new entity. The name becomes part of the primary key. :param key: Inherited from `Model`_. The explicit `Key`_ instance for the new entity. Cannot be used with ``key_name`` or ``parent``. If ``None``, falls back on the behavior for ``key_name`` and ``parent``. :param kwargs: Initial values for the instance's properties, as keyword arguments. Useful if subclassing. :return: An instance of the ``NdbImage`` class. """ if filename is not None: filename = filename.encode('ascii', 'ignore') if url is not None: url = url.encode('ascii', 'ignore') if blob_info is not None: kwargs['blob_key'] = blob_info.key() return cls.create_new_entity(**kwargs) if blob_key is not None: kwargs['blob_key'] = blob_key return cls.create_new_entity(**kwargs) if data is None: if url is not None: response = urlfetch.fetch(url) data = response.content mime_type = mime_type or response.headers.get( 'Content-Type', None) if filename is None: path = urlparse.urlsplit(url)[2] filename = path[path.rfind('/') + 1:] if data is None: raise images.BadImageError("No image data") image = cls.create_new_entity(source_url=url, **kwargs) mime_type = mime_type or mimetypes.guess_type( filename)[0] if filename else None mime_type = mime_type or 'application/octet-stream' if mime_type not in ['image/jpeg', 'image/png', 'image/gif']: message = "The image mime type (%s) isn't valid" % mime_type logging.warning(message) image.key.delete() raise images.BadImageError(message) filename = filename or "{0}{1}".format( image.key_as_string, mimetypes.guess_extension(mime_type)) gae_image = images.Image(data) current_format = gae_image.format new_format = None if mime_type == 'image/jpeg' and current_format != images.JPEG: new_format = images.JPEG if mime_type == 'image/png' and current_format != images.PNG: new_format = images.PNG if new_format is not None: data = images.crop(data, 0.0, 0.0, 1.0, 1.0, output_encoding=new_format, quality=100) previous_blob_info = image.blob_info blob_key = image.post_data(data, filename=filename, mime_type=mime_type) if blob_key is not None: image.blob_key = blob_key image.put() if previous_blob_info is not None: previous_blob_info.delete() return image.key.get()
def get(self): userId = self.user_id fsbid = self.request.get('fsbid',default_value="") tag = self.request.get('tag') mode = self.request.get('mode') toptext = self.request.get('toptext') bottomtext = self.request.get('bottomtext') tags = tag.split(',') imgId = '' family = 'Impact' size = '34' bid='' color = '#FFFFFF' style = 'normal' weight = 'normal' shadowcolor = "black" top = 20 left = 20 meme_query = MemeDb.query(MemeDb.mode == 'public').order(-MemeDb.date) meme_query = meme_query.filter(MemeDb.tags.IN(tags)); memes = meme_query.fetch(1) imgid = "" for meme in memes: imgid = meme.resid if imgid == "": self.response.write("NOTFOUND") return blob_reader = blobstore.BlobReader(imgid) background = images.Image(blob_reader.read()) selectionwidth = 500 selectionheight = 500 textlayers = [] tags = [] if 1 == 1: rows = 1 columns = 1 totalwidth = selectionwidth totalheight = selectionheight panelwidth = selectionwidth panelheight = selectionheight otype = 'normal' woffset = 0 hofsset = 0 rrindex = 0 rcindex = 0 textindex = 0 toptexts = [] bottomtexts = [] imgwidth = 500 imgheight = 500 background.resize(width=int(imgwidth), height=int(imgheight)) background.im_feeling_lucky() imgwidth = background.width imgheight = background.height thumbnail = background.execute_transforms(output_encoding=images.JPEG) back_layer = Image.new('RGBA', (totalwidth,totalheight), (204, 204, 204, 100)) output = StringIO.StringIO() back_layer.save(output, format="png") back_layer = output.getvalue() output.close() #merge merged = images.composite([(back_layer, 0,0, 1.0, images.TOP_LEFT), (thumbnail, (totalwidth-int(imgwidth))/2, (totalheight - int(imgheight))/2, 1.0, images.TOP_LEFT)], totalwidth, totalheight) toptexts.append(toptext) bottomtexts.append(bottomtext) textindex = 1 for bottomtext in bottomtexts: top = panelheight*(textindex - 1) + panelheight - 60 left = 20 textindex = textindex + 1 logging.info("%stoptext" %top) width = panelwidth height = 50 textVal = bottomtext text_img = Image.new('RGBA', (int(width),int(height)), (0, 0, 0, 0)) draw = ImageDraw.Draw(text_img) font=ImageFont.truetype(GetFontName(family,style,weight),int(size)) apString = '' lines = [] for x in range(0, len(textVal)): tempString = apString apString = apString + '%s' %textVal[x] width1, height1 = font.getsize(apString) if width1 >= int(width): lines.append(tempString) apString = '%s' %textVal[x] if apString != '': lines.append(apString) #lines = textwrap.wrap(textVal, width = 10) y_text = 0 for line in lines: font=ImageFont.truetype(GetFontName(family,style,weight),int(size)) width1, height1 = font.getsize(line) offset = (int(width) - int(width1))/2 draw.text((-2+offset, y_text-2), line, font=font, fill=shadowcolor) draw.text((+2+offset, y_text-2), line, font=font, fill=shadowcolor) draw.text((-2+offset, y_text+2), line, font=font, fill=shadowcolor) draw.text((+2+offset, y_text+2), line, font=font, fill=shadowcolor) draw.text((0+offset, y_text), line, font = font,fill=color) y_text += height1 # no write access on GAE output = StringIO.StringIO() text_img.save(output, format="png") text_layer = output.getvalue() output.close() textlayers.append(text_layer) merged = images.composite([(merged, 0,0, 1.0, images.TOP_LEFT), (text_layer, int(float(left)),int(float(top)), 1.0, images.TOP_LEFT)], totalwidth, totalheight) textindex = 1 for toptext in toptexts: top = 20 + panelheight*(textindex - 1) left = 20 textindex = textindex + 1 logging.info("%stoptext" %top) width = panelwidth height = 50 textVal = toptext text_img = Image.new('RGBA', (int(width),int(height)), (0, 0, 0, 0)) draw = ImageDraw.Draw(text_img) font=ImageFont.truetype(GetFontName(family,style,weight),int(size)) apString = '' lines = [] for x in range(0, len(textVal)): tempString = apString apString = apString + '%s' %textVal[x] width1, height1 = font.getsize(apString) if width1 >= int(width): lines.append(tempString) apString = '%s' %textVal[x] if apString != '': lines.append(apString) #lines = textwrap.wrap(textVal, width = 10) y_text = 0 for line in lines: font=ImageFont.truetype(GetFontName(family,style,weight),int(size)) width1, height1 = font.getsize(line) offset = (int(width) - int(width1))/2 draw.text((-2+offset, y_text-2), line, font=font, fill=shadowcolor) draw.text((+2+offset, y_text-2), line, font=font, fill=shadowcolor) draw.text((-2+offset, y_text+2), line, font=font, fill=shadowcolor) draw.text((+2+offset, y_text+2), line, font=font, fill=shadowcolor) draw.text((0+offset, y_text), line, font = font,fill=color) y_text += height1 # no write access on GAE output = StringIO.StringIO() text_img.save(output, format="png") text_layer = output.getvalue() output.close() textlayers.append(text_layer) merged = images.composite([(merged, 0,0, 1.0, images.TOP_LEFT), (text_layer, int(float(left)),int(float(top)), 1.0, images.TOP_LEFT)], totalwidth, totalheight) merged = images.crop(merged,float(0),float(0), 1.0,1.0) # save file_name = files.blobstore.create(mime_type='image/png') with files.open(file_name, 'a') as f: f.write(merged) files.finalize(file_name) blob_key = files.blobstore.get_blob_key(file_name) #memeid = SaveFinalMeme(userId,blob_key,tags,bid,mode) memeid = SaveMobileFinalMeme(userId,blob_key,tags,fsbid,mode) url = images.get_serving_url (blob_key, 500) UpdateGCM(self,'image',url) self.response.write ('%s' % url)
def post(self): self.checkSession(self.request.headers.get('Cookie')) login = str(self.request.get('logins')) if login != "": responsehtml = '' dbusers = db.GqlQuery("SELECT * FROM DBUser") max_users_in_list = 4 for dbuser in dbusers: if str(dbuser.login).find(login) >= 0 and max_users_in_list: max_users_in_list -= 1 if str(self.request.get("objectadd")) == "true": responsehtml += "<a style='cursor: pointer;' id='user" + str( max_users_in_list ) + "' onclick='$(\"#login\").attr(\"value\", $(\"#user" + str( max_users_in_list ) + "\").text()); $(\"#showlogins\").hide();'>" + str( dbuser.login) + "</a><br>" else: responsehtml += "<a href=/changeinfo/" + str( dbuser.key().id()) + ">" + str( dbuser.login) + "</a><br>" if login != "": self.response.out.write(responsehtml) else: need_delete = bool(self.request.get('delete')) if not need_delete: avatara = DBAvatara() data = self.request.get("img") if data: print "userava%s" % self.request.get('userid') memcache.delete("userava%s" % self.request.get('userid')) try: dbQuery = DBAvatara.gql( "WHERE userid = :dbuserid", dbuserid=int(self.request.get('userid'))) avataras = dbQuery.fetch(1) avatara = avataras[0] small = images.Image(data).width if images.Image( data).width < images.Image( data).height else images.Image(data).height avatar = images.crop( data, 0., 0., small / float(images.Image(data).width), small / float(images.Image(data).height)) avatar = images.resize(avatar, 128, 128) avatara.image = db.Blob(avatar) avatara.put() except: small = images.Image(data).width if images.Image( data).width < images.Image( data).height else images.Image(data).height avatar = images.crop( data, 0., 0., small / float(images.Image(data).width), small / float(images.Image(data).height)) avatar = images.resize(avatar, 128, 128) avatara.image = db.Blob(avatar) avatara.userid = int(self.request.get('userid')) avatara.put() else: dbQuery = db.GqlQuery( "SELECT __key__ FROM DBAvatara WHERE userid = :dbuserid", dbuserid=int(self.request.get('userid'))) db.delete(dbQuery) user = DBUser.get_by_id(int(self.request.get('userid'))) #editeduser = DBUser() user.name = cgi.escape(self.request.get('name')) user.surname = cgi.escape(self.request.get('surname')) user.about = cgi.escape(self.request.get('user_about')) user.twitter = cgi.escape(self.request.get('twitter')) user.livejournal = cgi.escape(self.request.get('livejournal')) answer = '<h1>Данные изменены</h1><br>' self.insertMenu() if user.email != self.request.get('email'): user.email = self.request.get('email') confirmation = hashlib.md5(str(random.random())).hexdigest() dbuser.confirmation = confirmation rc = RegisterConfirm() rc.sendEmailCheck(self.request.get('email'), confirmation) answer += '<h1>Почта была изменена и на новый адрес было выслано письмо для подтверждения регистрации</h1>' if self.request.get('password') != '': if user.password == hashlib.md5( self.request.get('oldpassword')).hexdigest(): user.password = hashlib.md5( self.request.get('password')).hexdigest() else: self.insertContent('<h1>Пароль не был изменен</h1><br>') user.put() self.insertContent('<h1>Данные изменены</h1>') self.drawPage()
def post(self): self.checkSession(self.request.headers.get('Cookie')) login = str(self.request.get('logins')) if login != "": responsehtml = '' dbusers = db.GqlQuery("SELECT * FROM DBUser") max_users_in_list = 4 for dbuser in dbusers: if str(dbuser.login).find(login) >= 0 and max_users_in_list: max_users_in_list -= 1 if str(self.request.get("objectadd")) == "true": responsehtml += "<a style='cursor: pointer;' id='user" + str(max_users_in_list) + "' onclick='$(\"#login\").attr(\"value\", $(\"#user" + str(max_users_in_list) + "\").text()); $(\"#showlogins\").hide();'>" + str(dbuser.login) + "</a><br>" else: responsehtml += "<a href=/changeinfo/" + str(dbuser.key().id()) + ">" + str(dbuser.login) + "</a><br>" if login != "": self.response.out.write(responsehtml) else: need_delete = bool(self.request.get('delete')) if not need_delete: avatara = DBAvatara() data = self.request.get("img") if data: print "userava%s" % self.request.get('userid') memcache.delete("userava%s" % self.request.get('userid')) try: dbQuery = DBAvatara.gql("WHERE userid = :dbuserid", dbuserid = int(self.request.get('userid'))) avataras = dbQuery.fetch(1) avatara = avataras[0] small = images.Image(data).width if images.Image(data).width < images.Image(data).height else images.Image(data).height avatar = images.crop(data, 0., 0., small/float(images.Image(data).width), small/float(images.Image(data).height)) avatar = images.resize(avatar, 128, 128) avatara.image = db.Blob(avatar) avatara.put() except: small = images.Image(data).width if images.Image(data).width < images.Image(data).height else images.Image(data).height avatar = images.crop(data, 0., 0., small/float(images.Image(data).width), small/float(images.Image(data).height)) avatar = images.resize(avatar, 128, 128) avatara.image = db.Blob(avatar) avatara.userid = int(self.request.get('userid')) avatara.put() else: dbQuery = db.GqlQuery("SELECT __key__ FROM DBAvatara WHERE userid = :dbuserid", dbuserid = int(self.request.get('userid'))) db.delete(dbQuery) user = DBUser.get_by_id(int(self.request.get('userid'))) #editeduser = DBUser() user.name = cgi.escape(self.request.get('name')) user.surname = cgi.escape(self.request.get('surname')) user.about = cgi.escape(self.request.get('user_about')) user.twitter = cgi.escape(self.request.get('twitter')) user.livejournal = cgi.escape(self.request.get('livejournal')) answer = '<h1>Данные изменены</h1><br>' self.insertMenu() if user.email != self.request.get('email'): user.email = self.request.get('email') confirmation = hashlib.md5(str(random.random())).hexdigest() dbuser.confirmation = confirmation rc = RegisterConfirm() rc.sendEmailCheck(self.request.get('email'), confirmation) answer += '<h1>Почта была изменена и на новый адрес было выслано письмо для подтверждения регистрации</h1>' if self.request.get('password') != '': if user.password == hashlib.md5(self.request.get('oldpassword')).hexdigest(): user.password = hashlib.md5(self.request.get('password')).hexdigest() else: self.insertContent('<h1>Пароль не был изменен</h1><br>') user.put() self.insertContent('<h1>Данные изменены</h1>') self.drawPage()
def create(cls, blob_key=None, blob_info=None, data=None, filename=None, url=None, mime_type=None, **kwargs): """ Create an ``Image``. Use this class method rather than creating an image with the constructor. You must provide one of the following parameters ``blob_info``, ``data``, or ``url`` to specify the image data to use. :param blob_key: The `Blobstore`_ data to use as the image data. If this parameter is not ``None``, all other parameters will be ignored as they are not needed (Only use with `NdbImage`). :param blob_info: The `Blobstore`_ data to use as the image data. If this parameter is not ``None``, all other parameters will be ignored as they are not needed (Do not use with `NdbImage`). :param data: The image data that should be put in the `Blobstore`_ and used as the image data. :param filename: The filename of the image data. If not provided, the filename will be guessed from the URL or, if there is no URL, it will be set to the stringified `Key`_ of the image entity. :param url: The URL to fetch the image data from and then place in the `Blobstore`_ to be used as the image data. :param mime_type: The `mime type`_ to use for the `Blobstore`_ image data. If ``None``, it will attempt to guess the mime type from the url fetch response headers or the filename. :param parent: Inherited from `Model`_. The `Model`_ instance or `Key`_ instance for the entity that is the new image's parent. :param key_name: Inherited from `Model`_. The name for the new entity. The name becomes part of the primary key. :param key: Inherited from `Model`_. The explicit `Key`_ instance for the new entity. Cannot be used with ``key_name`` or ``parent``. If ``None``, falls back on the behavior for ``key_name`` and ``parent``. :param kwargs: Initial values for the instance's properties, as keyword arguments. Useful if subclassing. :return: An instance of the ``NdbImage`` class. """ if filename is not None: filename = filename.encode('ascii', 'ignore') if url is not None: url = url.encode('ascii', 'ignore') if blob_info is not None: kwargs['blob_key'] = blob_info.key() return cls.create_new_entity(**kwargs) if blob_key is not None: kwargs['blob_key'] = blob_key return cls.create_new_entity(**kwargs) if data is None: if url is not None: response = urlfetch.fetch(url) data = response.content mime_type = mime_type or response.headers.get('Content-Type', None) if filename is None: path = urlparse.urlsplit(url)[2] filename = path[path.rfind('/')+1:] if data is None: raise images.BadImageError("No image data") image = cls.create_new_entity(source_url=url, **kwargs) mime_type = mime_type or mimetypes.guess_type(filename)[0] if filename else None mime_type = mime_type or 'application/octet-stream' if mime_type not in ['image/jpeg', 'image/png', 'image/gif']: message = "The image mime type (%s) isn't valid" % mime_type logging.warning(message) image.key.delete() raise images.BadImageError(message) filename = filename or "{0}{1}".format(image.key_as_string, mimetypes.guess_extension(mime_type)) gae_image = images.Image(data) current_format = gae_image.format new_format = None if mime_type == 'image/jpeg' and current_format != images.JPEG: new_format = images.JPEG if mime_type == 'image/png' and current_format != images.PNG: new_format = images.PNG if new_format is not None: data = images.crop(data, 0.0, 0.0, 1.0, 1.0, output_encoding=new_format, quality=100) previous_blob_info = image.blob_info blob_key = image.post_data(data, filename=filename, mime_type=mime_type) if blob_key is not None: image.blob_key = blob_key image.put() if previous_blob_info is not None: previous_blob_info.delete() return image.key.get()