Exemple #1
0
	def wallize(self):
		size = self.wall.width, self.wall.height
		print 'resising image to ', size
		filename = self.hash_file() + '.png'
		#bright = ImageEnhance.Brightness(im)
		#im = bright.enhance(0.5)
		#im.save('../tmp/' + filename, 'PNG')
		cuter.resize_and_crop(self.post.content_local_path, '../tmp/' + filename, size, crop_type='middle')
		return filename
def rotateimage(img,deg,makeThumb=True):
		im = Image.open(img)
		newimg = im.rotate(float(deg))
		newfile,ext =img.split('.')
		newfilename=startdir+str(time.time()).replace('.','')+'.'+ext
		newimg.save(newfilename)
		if(makeThumb):
			thumb,newthumb_ext = newfilename.replace('pics/','thumb/').split('.')
			cut.resize_and_crop(newfilename,thumb+'_thumb.'+newthumb_ext,[320,240])
			oldthumb,old_ext=img.replace('pics/','thumb/').split('.')
			os.remove(oldthumb+"_thumb."+old_ext)
		os.remove(img)
		print 'rotation',img
		return newfilename.replace(startdir,'')
def rotateimage(img, deg, makeThumb=True):
    im = Image.open(img)
    newimg = im.rotate(float(deg))
    newfile, ext = img.split('.')
    newfilename = startdir + str(time.time()).replace('.', '') + '.' + ext
    newimg.save(newfilename)
    if (makeThumb):
        thumb, newthumb_ext = newfilename.replace('pics/', 'thumb/').split('.')
        cut.resize_and_crop(newfilename, thumb + '_thumb.' + newthumb_ext,
                            [320, 240])
        oldthumb, old_ext = img.replace('pics/', 'thumb/').split('.')
        os.remove(oldthumb + "_thumb." + old_ext)
    os.remove(img)
    print 'rotation', img
    return newfilename.replace(startdir, '')
 def onMessage(self, payload, isBinary):
     global current_img, file_list
     if not isBinary:
         msg = "{} from {}".format(payload.decode('utf8'), self.peer)
         # self.factory.broadcast(msg)
         cmd = json.loads(payload)
         if (cmd.has_key("cmd")):
             print cmd
             if (cmd.has_key("img")
                 ):  #grab actual filename if json time was appended
                 oldname = cmd["img"]
                 cmd["img"] = cmd["img"].split('?')[0]
             if (cmd["cmd"] == "refresh"):
                 self.factory.broadcast(json.dumps({"refresh": "true"}))
             if (cmd["cmd"] == "getImages"):
                 print 'getting images'
                 self.sendMessage(
                     json.dumps({
                         "images": [
                             w.replace('pics/',
                                       'thumb/').replace('.', '_thumb.')
                             for w in file_list
                         ]
                     }))
                 print 'sent images'
             if (cmd["cmd"] == "getCurrentImage"):
                 self.sendMessage(json.dumps({"currentImg": current_img}))
             if (cmd["cmd"] == "setCurrentImage"):
                 current_img = cmd["value"].replace('_thumb', '').replace(
                     'thumb/', 'pics/')
                 self.factory.picChange(current_img)
             if (cmd["cmd"] == "remove"):
                 img2remove = cmd["img"].replace('_thumb', '').replace(
                     'thumb/', startdir)
                 thumb2remove = startdir.replace('pics', '') + cmd["img"]
                 os.remove(img2remove)
                 os.remove(thumb2remove)
                 img2remove = oldname.replace('_thumb', '').replace(
                     'thumb/', 'pics/')
                 if (img2remove in file_list):
                     file_list.remove(img2remove)
                     print 'image removed', img2remove
                 self.sendMessage(json.dumps({"imageRemoved": oldname}))
             if (cmd["cmd"] == "rotateImage"):
                 img = cmd["img"].replace('_thumb',
                                          '').replace('thumb/', startdir)
                 thumb = startdir.replace('pics', '') + cmd["img"]
                 newfilename, ext = rotateimage(img, int(
                     cmd["value"])).split('.')
                 self.sendMessage(
                     json.dumps({
                         "imageUpdate":
                         'thumb/' + newfilename + "_thumb." + ext,
                         "oldname":
                         oldname
                     }))
             if (cmd["cmd"] == "setConfig"):
                 self.factory.frameconfig.changeKey(
                     cmd['change'].keys()[0], cmd['change'].values()[0])
                 self.factory.sendNewConfig(self, all=True)
                 self.factory.callID.cancel(
                 )  #cancel any async calls for the picture frame ticks
                 self.factory.tick()
             if (cmd["cmd"] == "getConfig"):
                 self.factory.sendNewConfig(self)
         if (cmd.has_key("upload")):
             imgstring = cmd["upload"]
             appendage = str(time.time()).replace('.', '')
             strio = StringIO(imgstring.decode('base64'))
             strpath = startdir.replace(
                 'pics', 'thumb') + appendage + '_thumb.' + cmd['file_type']
             #create thumbnail
             if (cmd['file_type'] != "gif"):
                 cut.resize_and_crop(strio, strpath,
                                     [320, 240])  # ,crop_type='middle')
             else:
                 fh = open(
                     "/home/pi/piframe/www/thumb/" + appendage +
                     "_thumb.gif", "wb")
                 fh.write(imgstring.decode('base64'))
                 fh.close()
             #create original
             fh = open(
                 "/home/pi/piframe/www/pics/" + appendage + '.' +
                 cmd['file_type'], "wb")
             fh.write(imgstring.decode('base64'))
             fh.close()
             #change owner
             os.system('chown pi /home/pi/piframe/www/thumb/' + appendage +
                       '_thumb.' + cmd['file_type'])
             os.system('chown pi /home/pi/piframe/www/pics/' + appendage +
                       '.' + cmd['file_type'])
             file_list.append('pics/' + appendage + '.' + cmd['file_type'])
             self.factory.broadcast(
                 json.dumps({
                     "newImage":
                     "thumb/" + appendage + '_thumb.' + cmd['file_type']
                 }))
Exemple #5
0
    filename, ext = os.path.splitext(file)
    e = ext.lower()
    if e in extensions:
        if (file not in file_list):
            file_list.append(file)
    else:
        print 'Skipping: ', file, ' (NOT a supported image)'


if __name__ == '__main__':
    if len(sys.argv) > 1:
        walktree(sys.argv[1], addtolist)
        thumbdir = sys.argv[2]
        if thumbdir.endswith('/'):
            thumbdir = thumbdir.rstrip('/')
            print 'Modified thumbdir: ', thumbdir
        for file in file_list:
            filename, ext = file.replace(sys.argv[1], '').split('.')
            thumbfilename = thumbdir + '/' + filename + '_thumb.' + ext
            #check if file exists already and create it otherwise
            if (not os.path.isfile(thumbfilename)):
                if (ext != 'gif'):
                    cut.resize_and_crop(file, thumbfilename, [320, 240])
                    print thumbfilename
                else:
                    #since pillow can't resize gif too well we just copy it over
                    c.copyfile(file, thumbfilename)
                    print thumbfilename
            else:
                print 'file exists skipping', thumbfilename
            print 'Skipping %s' % pathname

def addtolist(file, extensions=['.png', '.jpg', '.jpeg', '.gif', '.bmp']):
    """Add a file to a global list of image files."""
    global file_list  
    filename, ext = os.path.splitext(file)
    e = ext.lower()
    if e in extensions:
        if (file not in file_list):
            file_list.append(file)
    else:
        print 'Skipping: ', file, ' (NOT a supported image)'

if __name__ == '__main__':
	if len(sys.argv) > 1:
		walktree(sys.argv[1],addtolist)
		thumbdir=sys.argv[2]
		for file in file_list:
			filename,ext = file.replace(sys.argv[1],'').split('.')
			thumbfilename=thumbdir+'/'+filename+'_thumb.'+ext
			#check if file exists already and create it otherwise
			if(not os.path.isfile(thumbfilename)):
				if(ext!='gif'):
					cut.resize_and_crop(file,thumbfilename,[320, 240])
					print thumbfilename
				else:
					#since pillow can't resize gif too well we just copy it over
					c.copyfile(file,thumbfilename)
					print thumbfilename
			else:
				print 'file exists skipping',thumbfilename
    def onMessage(self, payload, isBinary):
        global current_img,file_list
        if not isBinary:
            msg = "{} from {}".format(payload.decode('utf8'), self.peer)
            # self.factory.broadcast(msg)
            cmd = json.loads(payload)
            if (cmd.has_key("cmd")):
				print cmd
				if(cmd.has_key("img")):#grab actual filename if json time was appended
					oldname = cmd["img"]
					cmd["img"]=cmd["img"].split('?')[0]
				if(cmd["cmd"]=="refresh"):
					self.factory.broadcast(json.dumps({"refresh":"true"}))
				if(cmd["cmd"]=="getImages"):
					print 'getting images'
					self.sendMessage(json.dumps({"images":[w.replace('pics/','thumb/').replace('.','_thumb.') for w in file_list]}));
					print 'sent images'
				if(cmd["cmd"]=="getCurrentImage"):
					self.sendMessage(json.dumps({"currentImg":current_img}))
				if(cmd["cmd"]=="setCurrentImage"):
					current_img=cmd["value"].replace('_thumb','').replace('thumb/','pics/')
					self.factory.picChange(current_img)
				if(cmd["cmd"]=="remove"):
					img2remove=cmd["img"].replace('_thumb','').replace('thumb/',startdir)
					thumb2remove = startdir.replace('pics','')+cmd["img"];
					os.remove(img2remove)
					os.remove(thumb2remove)
					img2remove=oldname.replace('_thumb','').replace('thumb/','pics/')
					if(img2remove in file_list):
						file_list.remove(img2remove)
						print 'image removed',img2remove
					self.sendMessage(json.dumps({"imageRemoved":oldname}))
				if(cmd["cmd"]=="rotateImage"):
					img = cmd["img"].replace('_thumb','').replace('thumb/',startdir)
					thumb = startdir.replace('pics','')+cmd["img"];
					newfilename,ext=rotateimage(img,int(cmd["value"])).split('.')
					self.sendMessage(json.dumps({"imageUpdate":'thumb/'+newfilename+"_thumb."+ext,"oldname":oldname}))
				if(cmd["cmd"]=="setConfig"):
					self.factory.frameconfig.changeKey(cmd['change'].keys()[0],cmd['change'].values()[0])
					self.factory.sendNewConfig(self,all=True)
					self.factory.callID.cancel()#cancel any async calls for the picture frame ticks
					self.factory.tick()
				if(cmd["cmd"]=="getConfig"):
					self.factory.sendNewConfig(self)
            if (cmd.has_key("upload")):
                imgstring = cmd["upload"]
                appendage = str(time.time()).replace('.', '')
                strio = StringIO(imgstring.decode('base64'))
                strpath = startdir.replace('pics','thumb') + appendage + '_thumb.'+cmd['file_type']
				#create thumbnail
                if(cmd['file_type']!="gif"):
                    cut.resize_and_crop(strio, strpath, [320, 240])  # ,crop_type='middle')
                else:
                    fh = open("/home/pi/piframe/www/thumb/" + appendage + "_thumb.gif", "wb")
                    fh.write(imgstring.decode('base64'))
                    fh.close()
                #create original
                fh = open("/home/pi/piframe/www/pics/" + appendage+ '.'+cmd['file_type'], "wb")
                fh.write(imgstring.decode('base64'))
                fh.close()
				#change owner
                os.system('chown pi /home/pi/piframe/www/thumb/' + appendage + '_thumb.'+cmd['file_type']);
                os.system('chown pi /home/pi/piframe/www/pics/' + appendage + '.'+cmd['file_type']);
                file_list.append('pics/' + appendage + '.'+cmd['file_type']);
                self.factory.broadcast(json.dumps({"newImage":"thumb/" + appendage + '_thumb.'+cmd['file_type']}));