def main(): selection = dialogs.alert('Type', '', 'Encrypt', 'Decrypt') if selection == 1: i = dialogs.alert('Image', '', 'Take Photo', 'Select from Photos') if i == 1: im = photos.capture_image() else: im = photos.pick_image() im.thumbnail( (430, 430)) if im.size[0] > 430 or im.size[1] > 430 else None # im, im_arr = load_image("Test.img") im_arr = im.load() x_size, y_size = im.size basic_encrypt_scramble(im_arr, x_size, y_size) two_key_encryption(im_arr, x_size, y_size, 123, 4574574) im.show() save_image(input("Name (example.png):"), im) else: i = dialogs.alert('Image', '', 'Load Image', 'Select from Photos') if i == 1: im = Image.open(input("Name (example.png): ")) else: im = photos.pick_image() n, d = (int(num) for num in input("(n, d) = ").split(",")) im_arr = im.load() x_size, y_size = im.size two_key_decryption(im_arr, x_size, y_size, 123, 4574574) basic_decrypt_unscramble(im_arr, x_size, y_size, n, d) im.show() save_image(input("Name (example.png): "), im)
def btn_GetPic(self, sender): bytestring = photos.pick_image(raw_data=True) png = bytearray.fromhex('89504E47') jpg = bytearray.fromhex('FFD8FF') gif = bytearray.fromhex('474946') bmp = bytearray.fromhex('424D') tif = bytearray.fromhex('49492A') ext = '' if bytestring[0:4] == png: ext = '.png' elif bytestring[0:3] == jpg: ext = '.jpg' elif bytestring[0:3] == gif: ext = '.gif' elif bytestring[0:2] == bmp: ext = '.bmp' elif bytestring[0:3] == tif: ext = '.tif' else: self.btn_Help(None,message="Unknown image type! (Only png, jpg, gif, bmp and tif are supported)",name='Error') return size = len(bytestring) for i in xrange(sys.maxint): filename = 'image{}'.format(str(i).zfill(3)) + ext if not os.path.exists(filename): file = open(self.path + '/' + filename, 'wb') file.write(bytestring) break self.make_lst() self.view['tableview1'].reload_data() console.hud_alert(filename + ' / ' + str(size / 1024) + ' kB', duration = 3.0)
def main(): store = CNContactStore.alloc().init().autorelease() # Find the first contact that matches the name. pred = CNContact.predicateForContactsMatchingName_(CONTACT_NAME) fetch_keys = ['imageDataAvailable', 'imageData'] people = store.unifiedContactsMatchingPredicate_keysToFetch_error_(pred, fetch_keys, None) if not people: print 'No person found with the name "%s"' % (CONTACT_NAME,) return p = people[0] has_image = p.imageDataAvailable() if has_image: # Show the existing picture of the contact: img_data = p.imageData() img_data_str = string_at(img_data.bytes(), img_data.length()) img = ui.Image.from_data(img_data_str) img.show() # Pick a new image from photos: new_img_data = photos.pick_image(raw_data=True) if new_img_data: # Note: objc_util automatically converts bytearray to NSData new_img_bytes = bytearray(new_img_data) # Create a mutable copy of the fetched contact... mutable_contact = p.mutableCopy().autorelease() # Assign new image data... mutable_contact.imageData = new_img_bytes # Create a save request for he contact, and execute it... save_req = CNSaveRequest.new().autorelease() save_req.updateContact_(mutable_contact) store.executeSaveRequest_error_(save_req, None)
def main(): store = CNContactStore.alloc().init().autorelease() # Find the first contact that matches the name. pred = CNContact.predicateForContactsMatchingName_(CONTACT_NAME) fetch_keys = ['imageDataAvailable', 'imageData'] people = store.unifiedContactsMatchingPredicate_keysToFetch_error_( pred, fetch_keys, None) if not people: print('No person found with the name "%s"' % (CONTACT_NAME, )) return p = people[0] has_image = p.imageDataAvailable() if has_image: # Show the existing picture of the contact: img_data = p.imageData() img_data_str = string_at(img_data.bytes(), img_data.length()) img = ui.Image.from_data(img_data_str) img.show() # Pick a new image from photos: new_img_data = photos.pick_image(raw_data=True) if new_img_data: # Note: objc_util automatically converts bytearray to NSData new_img_bytes = bytearray(new_img_data) # Create a mutable copy of the fetched contact... mutable_contact = p.mutableCopy().autorelease() # Assign new image data... mutable_contact.imageData = new_img_bytes # Create a save request for he contact, and execute it... save_req = CNSaveRequest.new().autorelease() save_req.updateContact_(mutable_contact) store.executeSaveRequest_error_(save_req, None)
def PythonistaTest(): '''A test of the module for iOS devices running Pythonista''' import console,photos,clipboard #Ask the user to either take a photo or choose an existing one capture = console.alert("Image2ASCII", button1="Take Photo", button2="Pick Photo") if capture == 1: im = photos.capture_image() elif capture == 2: im = photos.pick_image(original=False) photos.save_image(im) console.show_activity() out = image2ASCII(im, 200) outim = RenderASCII(out, bgcolor = '#ededed') stitchImages(im, outim).show() console.hide_activity() outim.save('image.jpg') console.quicklook('image.jpg') mode = console.alert("Image2ASCII", "You can either:","Share Text","Share Image") if mode == 1: file = open('output.txt', 'w') file.write(out) file.close() console.open_in('output.txt') elif mode == 2: console.open_in('image.jpg') time.sleep(5) console.clear()
def main(): console.alert('Shortcut Generator', 'This script adds a "Webclip" shortcut to your homescreen. The shortcut can be used to open a web page in full-screen mode, or to launch a custom URL (e.g. a third-party app). You\'ll be asked for a title, a URL, and an icon (from your camera roll).', 'Continue') label = console.input_alert('Shortcut Title', 'Please enter a short title for the homescreen icon.', '', 'Continue') if not label: return url = console.input_alert('Shortcut URL', 'Please enter the full URL that the shortcut should launch.', '', 'Continue') if not url: return icon = photos.pick_image() if not icon: return console.show_activity('Preparing Configuration profile...') data_buffer = BytesIO() icon.save(data_buffer, 'PNG') icon_data = data_buffer.getvalue() unique_id = uuid.uuid4().urn[9:].upper() config = {'PayloadContent': [{'FullScreen': True, 'Icon': plistlib.Data(icon_data), 'IsRemovable': True, 'Label': label, 'PayloadDescription': 'Configures Web Clip', 'PayloadDisplayName': label, 'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 'PayloadOrganization': 'omz:software', 'PayloadType': 'com.apple.webClip.managed', 'PayloadUUID': unique_id, 'PayloadVersion': 1, 'Precomposed': True, 'URL': url}], 'PayloadDescription': label, 'PayloadDisplayName': label + ' (Shortcut)', 'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 'PayloadOrganization': 'omz:software', 'PayloadRemovalDisallowed': False, 'PayloadType': 'Configuration', 'PayloadUUID': unique_id, 'PayloadVersion': 1} console.hide_activity() run_server(config)
def __init__(self, image_mask=None, *args, **kwargs): ui.View.__init__(self, *args, **kwargs) self.iv = ui.ImageView() self.iv.image = ui.Image.from_data(photos.pick_image(raw_data=True)) self.add_subview(self.iv) self.add_subview(image_mask)
def btn_load(self, sender): print('btn_load') self.scvrate = 1 self.scvrate0 = 1 self.base_image = ui.Image.from_data(photos.pick_image(raw_data=True)) self.image_w, self.image_h = self.base_image.size #元画像の幅と高さpil.sizeメソッド self.pv.image_w, self.pv.image_h = self.image_w, self.image_h self.biv.frame = (0, 0, self.image_w, self.image_h) #元画像のサイズにbivを変更 self.scv.content_size = (self.image_w, self.image_h) #元画像を入れる枠のサイズを宣言 w, h = ui.get_screen_size() #画面サイズを取得。xとかクラス名除く部分。 self.scr_w, self.scr_h = w, h #全画面の幅と高さ self.scvrate0 = self.scvrate #*2 self.biv.image = self.base_image #元画像をbivに代入。 self.zoom_set(sender) #titleに画像サイズと倍率を表示 self.name = 'Size:' + str(int(self.image_w)) + ', ' + str( int(self.image_h)) + ' rate:' + str( self.scvrate) + ' ' + self.filename1 self.set_needs_display()
def do_GET(self): if os.path.splitext(self.path)[1] == '.html': self.send_response(200) self.send_header("Content-type", 'text/html') self.send_header("Last-Modified", self.date_time_string()) self.end_headers() self.wfile.write( '<!DOCTYPE html><html><head><meta charset="utf-8"><script src="../ckeditor/ckeditor.js"></script></head><body><textarea cols="1" id="editor1" name="editor1" rows="1"></textarea><script>CKEDITOR.replace("editor1",{on: {}});</script></body></html>' ) elif os.path.splitext(self.path)[1] == '.jpg': try: bI = _gdI[self.path[1:]] except: with io.BytesIO() as bIO: ip = photos.pick_image(show_albums=True) ip.save(bIO, ip.format) bI = bIO.getvalue() _gdI[self.path[1:]] = bI self.send_response(200) self.send_header("Content-type", 'image/jpeg') self.send_header("Content-Length", str(len(bI))) self.send_header("Last-Modified", self.date_time_string()) self.end_headers() self.wfile.write(bI) else: SimpleHTTPRequestHandler.do_GET(self)
def decode(): i = dialogs.alert('Image', '', 'Load Image', 'Select from Photos') if i == 1: im = Image.open(input("Name (example.png): ")) else: im = photos.pick_image() data = '' imgdata = iter(im.getdata()) while (True): pixels = [ value for value in imgdata.__next__()[:3] + imgdata.__next__()[:3] + imgdata.__next__()[:3] ] # string of binary data binstr = '' for i in pixels[:8]: if (i % 2 == 0): binstr += '0' else: binstr += '1' data += chr(int(binstr, 2)) if (pixels[-1] % 2 != 0): return data
def PythonistaTest(): '''A test of the module for iOS devices running Pythonista''' import console, photos, clipboard #Ask the user to either take a photo or choose an existing one capture = console.alert("Image2ASCII", button1="Take Photo", button2="Pick Photo") if capture == 1: im = photos.capture_image() elif capture == 2: im = photos.pick_image(original=False) photos.save_image(im) console.show_activity() out = image2ASCII(im, 200) outim = RenderASCII(out, bgcolor='#ededed') stitchImages(im, outim).show() console.hide_activity() outim.save('image.jpg') console.quicklook('image.jpg') mode = console.alert("Image2ASCII", "You can either:", "Share Text", "Share Image") if mode == 1: file = open('output.txt', 'w') file.write(out) file.close() console.open_in('output.txt') elif mode == 2: console.open_in('image.jpg') time.sleep(5) console.clear()
def main(): if not photos.get_count(): print('Sorry no access or no pictures.') return image = photos.pick_image() if not image: print('No image selected. Good bye!') return resize = False quality = 95 width, height = image.size megapixels = round(width * height / 1000000.0, 1) image_mode = image.mode print(pic_info_menu_fmt.format(**{ 'width' : width, 'height' : height, 'megapixels' : megapixels, 'image_mode' : image_mode })) option = int(raw_input('Resolution: ')) if option not in (0, 1, 2, 3, 5): print('Cancel: {} is not valid input.'.format(option)) return if option == 0: quality /= 100.0 elif option == 1: image_mode, quality = pic_para(image_mode) elif option == 2: print('\nChanging the ratio causes picture deformation!') width2 = int(raw_input('Width: ')) ratio = width / (height * 1.0) suggestion = width2 / ratio height2 = int(raw_input('Height [Enter = {:.0f}]:'.format(suggestion)) or suggestion) if (width2 == width and height2 == height): resize = False else: resize = True width = width2 height = height2 image_mode, quality = pic_para(image_mode) elif option == 3: resolution3megapixel = (2048, 1536) resize = not (width in resolution3megapixel and height in resolution3megapixel) if resize: if width >= height: # Landscape or Square width, height = resolution3megapixel # Landscape else: height, width = resolution3megapixel # Portrait image_mode, quality = pic_para(image_mode) elif option == 5: resolution5megapixel = (2592, 1936) resize = not (width in resolution5megapixel and height in resolution5megapixel) if resize: if width >= height: # Landscape or Square width, height = resolution5megapixel # Landscape else: height, width = resolution5megapixel # Portrait image_mode, quality = pic_para(image_mode) pic_save(image, image_mode, width, height, quality, resize)
def main(): console.alert( 'Shortcut Generator', 'This script adds a "Webclip" shortcut to your homescreen. The shortcut can be used to open a web page in full-screen mode, or to launch a custom URL (e.g. a third-party app). You\'ll be asked for a title, a URL, and an icon (from your camera roll).', 'Continue') label = console.input_alert( 'Shortcut Title', 'Please enter a short title for the homescreen icon.', '', 'Continue') if not label: return url = console.input_alert( 'Shortcut URL', 'Please enter the full URL that the shortcut should launch.', '', 'Continue') if not url: return icon = photos.pick_image() if not icon: return console.show_activity('Preparing Configuration profile...') data_buffer = BytesIO() icon.save(data_buffer, 'PNG') icon_data = data_buffer.getvalue() unique_id = uuid.uuid4().urn[9:].upper() config = { 'PayloadContent': [{ 'FullScreen': True, 'Icon': plistlib.Data(icon_data), 'IsRemovable': True, 'Label': label, 'PayloadDescription': 'Configures Web Clip', 'PayloadDisplayName': label, 'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 'PayloadOrganization': 'omz:software', 'PayloadType': 'com.apple.webClip.managed', 'PayloadUUID': unique_id, 'PayloadVersion': 1, 'Precomposed': True, 'URL': url }], 'PayloadDescription': label, 'PayloadDisplayName': label + ' (Shortcut)', 'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 'PayloadOrganization': 'omz:software', 'PayloadRemovalDisallowed': False, 'PayloadType': 'Configuration', 'PayloadUUID': unique_id, 'PayloadVersion': 1 } console.hide_activity() run_server(config)
def btn_load(self, sender): self.bgview.image = ui.Image.from_data(photos.pick_image(raw_data=True)) self.bgview.layout() self.name = 'Size: ' + str(self.bgview.image.size) self.layout() self.bgview.set_needs_display() if self.bgview.image: self.olview.bgview_image = True
def main(): set_img = photos.pick_image() photos.save_image(set_img) console.clear() print "Generating image..." console.show_activity() sketch(set_img).show() console.hide_activity()
def select_photos(): console.clear() back = MyView(frame=(0, 0, 500, 500)) back.present('sheet') todels = photos.pick_image(include_metadata=True, original=True, raw_data=False, multi=True)
def pick(a): global base temp = photos.pick_image() if not temp is None: base = render(temp, 726, 589) root['canvas'].rebase() refresh() hud_alert('Loaded')
def get_image(sender): view = sender.superview image = view['Image'] try: image.image = ui.Image.from_data(photos.pick_image(raw_data=True)) except: view.close() raise
def __init__(self): self.img2 = photos.pick_image() self.img = self.img2.convert('RGBA') #fix for current scene.load_pil_image() if self.img: self.picsize = scene.Size(*self.img.size) scene.run(self) else: print('Good bye!')
def btn_GetPic(self, sender): img = photos.pick_image() if not img: return for i in xrange(sys.maxint): filename = '{}/image{}.jpg'.format(self.path, str(i).zfill(3)) if not os.path.exists(filename): img.save(filename, 'JPEG') break self.make_lst() self.view['tableview1'].reload_data()
def __init__(self, width, height): self.frame = (0,0,width,height) self.iwidth = 300 self.iheight = 200 framesize = 10 self.img = ui.Image.from_data(photos.pick_image(raw_data=True)) #w, h = self.img.size #print 'img size: ' + str(w) + ' x ' + str(h) with ui.ImageContext(self.iwidth, self.iheight) as ctx: self.img.draw(framesize,framesize,self.iwidth-2*framesize,self.iheight-2*framesize) self.img = ctx.get_image()
def btn_load(self, sender): self.bgview.image = ui.Image.from_data( photos.pick_image(raw_data=True)) self.bgview.layout() self.name = 'Size: ' + str(int( self.bgview.image.size[0])) + ', ' + str( int(self.bgview.image.size[1])) self.olview.org_size = self.bgview.image.size self.layout() self.bgview.set_needs_display() if self.bgview.image: self.olview.bgview_image = True
def open_action(sender, img=None): global md if img is None: img = photos.pick_image(show_albums=True) md.hd_img = img.copy() md.hd_img.thumbnail(hdsize) img.thumbnail(thbsize) md.orig_ary = np.asarray(img)/255.0 md.orig_img = uiimg_from_array(md.orig_ary) # update ui img_view = v['theImage'] img_view.image = md.orig_img
def select_photos(): console.clear() back = MyView(frame=(0, 0, 500, 500)) back.present('sheet') todels = photos.pick_image(include_metadata=True, original=True, raw_data=False, multi=True) # todels = list of tuples # [(image,metadata),(image,metadata),...] # Build dictionary filename: index fn_index = {} for ip in range(photos.get_count()): m = photos.get_metadata(ip) fn = m.get('filename') fn_index[fn] = ip # that could be a problem if two photos have the same filename, what happens if you download the same file (fi from Dropbox) more than once. # pick_image seems to display "camera roll" which seems to be all photos in sequence like # - type = 2: smartalbum # - subtype = 209: smartalbumlibrary result = PHAssetCollection.fetchAssetCollectionsWithType_subtype_options_( 2, 209, None) coll = result.firstObject() assets = PHAsset.fetchAssetsInAssetCollection_options_(coll, None) # create array of assets to be deleted a_del = [] for todel in todels: fn = todel[1].get('filename') ia = fn_index[fn] # file name -> index a = assets.objectAtIndex_(ia) resources = PHAssetResource.assetResourcesForAsset(a) filename = resources[0].originalFilename a_del.append(a) lib = PHPhotoLibrary.sharedPhotoLibrary() def change_block(): # standard delete will ask a confirmation by specifying the number of photos to be deleted but by showing only one req = PHAssetChangeRequest.deleteAssets_(a_del) def perform_changes(): lib.performChangesAndWait_error_(change_block, None) t = threading.Thread(target=perform_changes) t.start() t.join()
def webclip(payload): form = [{'title':'URL','type':'url','key':'url'}, {'title':'Title','key':'label','type':'text'}, {'title':'Removable','key':'removable','type':'switch','value':True}, {'title':'Fullscreen','key':'fullscreen','type':'switch','value':False}, {'title':'Precomposed','key':'precomposed','type':'switch','value':True}, {'title':'image','key':'icon','type':'switch','value':False}] + common_form returns = dialogs.form_dialog('Webclip',form) image = None if returns['icon']: returns['icon'] = photos.pick_image(True) if returns: payload.webclip(**stripestring(returns))
def webclip(payload): form = [{'title':'URL','type':'url','key':'url'}, {'title':'Title','key':'label','type':'text'}, {'title':'Removable','key':'removable','type':'switch','value':True}, {'title':'Fullscreen','key':'fullscreen','type':'switch','value':False}, {'title':'Precomposed','key':'precomposed','type':'switch','value':True}, {'title':'image','key':'icon','type':'switch','value':False}] + common_form returns = dialogs.form_dialog('Webclip',form) image = None if returns['icon']: returns['icon'] = photos.pick_image(True) if returns: payload.webclip(**returns)
def main(): images = photos.pick_image(multi=True, original=upload_originals, raw_data=upload_originals) if images is None: return for i, img in enumerate(images): print('Uploading image %i/%i...' % (i + 1, len(images))) if not upload_originals: b = BytesIO() img.save(b, 'JPEG', quality=jpeg_quality) data = b.getvalue() else: data = img r = requests.post('http://how-old.net/Home/Analyze?isTest=False', files={'file': ('someimage.jpg', data)}) d = json.loads(json.loads(r.text)) faces = d.get('Faces') ui_img = ui.Image.from_data(data) scale = result_size / max(ui_img.size) w, h = ui_img.size[0] * scale, ui_img.size[1] * scale with ui.ImageContext(w, h) as ctx: ui_img.draw(0, 0, w, h) for face in faces: rect = [ float(face['faceRectangle'][key]) * scale for key in ['left', 'top', 'width', 'height'] ] caption_rect = (rect[0], rect[1], max(40, rect[2]), 16) ui.set_color((0, 0, 0, 0.5)) ui.Path.rect(*rect).stroke() ui.fill_rect(*caption_rect) attrs = face['attributes'] age = attrs['age'] if age % 1.0 == 0: age = int(age) caption = '%s (%s)' % (age, attrs['gender'][0]) ui.draw_string(caption, caption_rect, color='white') result_img = ctx.get_image() result_img.show() if faces: faces_str = ', '.join([ '%s (%s)' % (face['attributes']['age'], face['attributes']['gender']) for face in faces ]) print('%i face%s: %s' % (len(faces), 's' if len(faces) != 1 else '', faces_str)) else: print('No faces found') print('Done')
def __init__(self): self.text = raw_input('Text to insert in the picture [Hello]: ') or 'Hello' self.position = None self.fontnr = 0 # Helvetica self.colornr = 3 # red self.fontsize = 48.0 # 48 point self.img2 = photos.pick_image() self.img = self.img2.convert('RGBA') #fix for current scene.load_pil_image() self.picsize = scene.Size(*self.img.size) self.btn_height = 0 if self.img: scene.run(self, frame_interval=3) # save battery with less frame rates -> 3 = 20fps else: print('Good bye!')
def main(): effect = dialogs.alert('Select Effect', '', 'Sketch', 'Emboss', 'Color Tiles') i = dialogs.alert('Image', '', 'Demo Image', 'Select from Photos') if i == 1: img = Image.open('test:Lenna') else: img = photos.pick_image() if effect == 1: sketch(img).show() elif effect == 2: emboss(img).show() else: color_tiles(img).show() print 'Tip: You can tap and hold the image to save it to your photo library.'
def main(): effect = dialogs.alert('Select Effect', '', 'Sketch', 'Emboss', 'Color Tiles') i = dialogs.alert('Image', '', 'Demo Image', 'Select from Photos') if i == 1: img = Image.open('test:Lenna') else: img = photos.pick_image() if effect == 1: sketch(img).show() elif effect == 2: emboss(img).show() else: color_tiles(img).show() print('Tip: You can tap and hold the image to save it to your photo library.')
def encode(msg): i = dialogs.alert('Image', '', 'Take Photo', 'Load Image', 'Select from Photos') if i == 1: im = photos.capture_image() elif i == 2: im = Image.open(input("Name (example.png): ")) else: im = photos.pick_image() newimg = im.copy() encode_enc(newimg, msg) newimg.show() new_img_name = input("Name (example.png): ") newimg.save(new_img_name, str(new_img_name.split(".")[1].upper())) print("Image saved")
def __init__(self): self.distance_old = 0.0 self.distance_new = 0.0 self.distance_abs = 0.0 self.reset = True self.zoom = 1.0 #no zoom self.zoom_min = 0.5 self.zoom_max = 5 self.zoom_speed = 3 self.img2 = photos.pick_image() self.img = self.img2.convert('RGBA') #fix for current scene.load_pil_image() if self.img: self.picsize = scene.Size(*self.img.size) scene.run(self) else: print('Good bye!')
def __init__(self): self.text = raw_input( 'Text to insert in the picture [Hello]: ') or 'Hello' self.position = None self.fontnr = 0 # Helvetica self.colornr = 3 # red self.fontsize = 48.0 # 48 point self.img2 = photos.pick_image() self.img = self.img2.convert( 'RGBA') #fix for current scene.load_pil_image() self.picsize = scene.Size(*self.img.size) self.btn_height = 0 if self.img: scene.run(self, frame_interval=3 ) # save battery with less frame rates -> 3 = 20fps else: print('Good bye!')
def __init__(self): self.text = raw_input('Text to insert in the picture [Hello]: ') or 'Hello' self.position = None self.fontnr = 0 # Helvetica self.colornr = 3 # red self.fontsize = 48.0 # 48 point self.img = photos.pick_image() self.picsize = scene.Size(*self.img.size) if self.picsize.h > self.picsize.w: print('Sorry at the moment only landscape or square pictures are supported!') self.img = None self.picborder = None self.btn_height = 0 if self.img: scene.run(self) else: print('Good bye!')
def __init__(self): scene.Scene.__init__(self) self.distance_old = 0.0 self.distance_new = 0.0 self.distance_abs = 0.0 self.reset = True self.zoom = 1.0 #no zoom self.zoom_min = 0.5 self.zoom_max = 5 self.zoom_speed = 3 self.img2 = photos.pick_image() self.img = self.img2.convert( 'RGBA') #fix for current scene.load_pil_image() if self.img: self.picsize = scene.Size(*self.img.size) scene.run(self) else: print('Good bye!')
def btn_GetPic(self, sender): img = photos.pick_image() if img == None: return counter = 0 ct_str = '000' while os.path.exists(self.path + '/' + 'image' + ct_str + '.jpg'): counter += 1 if counter > 9: if counter > 99: ct_str = str(counter) else: ct_str = '0' + str(counter) else: ct_str = '00' + str(counter) img.save(self.path + '/' + 'image' + ct_str + '.jpg', 'JPEG') self.make_lst() self.view['tableview1'].reload_data()
def pickimage(sender): url = "https://upload.twitter.com/1.1/media/upload.json?command=INIT&total_bytes=56&media_type=image/jpeg" image = photos.pick_image() imagedata = {"media": b'image'} req_media = tw.twitter.post(url, files=imagedata) print(req_media.text) # Media ID を取得 media_id = json.loads(req_media.text)['media_id'] print("Media ID: %d" % media_id) # Media ID を付加してテキストを投稿 params = {'status': '画像投稿テスト', "media_ids": [media_id]} req_media = tw.twitter.post(tw.statuses_update, params=params) if req_media.status_code != 200: print("画像のアップロードに失敗したのだ。")
def encode(): i = dialogs.alert('Image', '', 'Take Photo', 'Load Image', 'Select from Photos') if i == 1: im = photos.capture_image() elif i == 2: im = Image.open(input("Name (example.png): ")) else: im = photos.pick_image() data = input("Enter data to be encoded: ") if (len(data) == 0): raise ValueError('Data is empty') newimg = im.copy() encode_enc(newimg, data) new_img_name = input("Name (example.png): ") newimg.show() newimg.save(new_img_name, str(new_img_name.split(".")[1].upper())) print("Image saved")
def main(): images = photos.pick_image(multi=True, original=upload_originals, raw_data= upload_originals) if images is None: return for i, img in enumerate(images): print 'Uploading image %i/%i...' % (i+1, len(images)) if not upload_originals: b = BytesIO() img.save(b, 'JPEG', quality=jpeg_quality) data = b.getvalue() else: data = img r = requests.post('http://how-old.net/Home/Analyze?isTest=False', files={'file': ('someimage.jpg', data)}) d = json.loads(json.loads(r.text)) faces = d.get('Faces') ui_img = ui.Image.from_data(data) scale = result_size / max(ui_img.size) w, h = ui_img.size[0] * scale, ui_img.size[1] * scale with ui.ImageContext(w, h) as ctx: ui_img.draw(0, 0, w, h) for face in faces: rect = [float(face['faceRectangle'][key]) * scale for key in ['left', 'top', 'width', 'height']] caption_rect = (rect[0], rect[1], max(40, rect[2]), 16) ui.set_color((0, 0, 0, 0.5)) ui.Path.rect(*rect).stroke() ui.fill_rect(*caption_rect) attrs = face['attributes'] age = attrs['age'] if age % 1.0 == 0: age = int(age) caption = '%s (%s)' % (age, attrs['gender'][0]) ui.draw_string(caption, caption_rect, color='white') result_img = ctx.get_image() result_img.show() if faces: faces_str = ', '.join(['%s (%s)' % (face['attributes']['age'], face['attributes']['gender']) for face in faces]) print '%i face%s: %s' % (len(faces), 's' if len(faces) != 1 else '', faces_str) else: print 'No faces found' print 'Done'
def __init__(self): self.view = ui.load_view('PhotoTextV2') self.set_button_actions() self.view.present('full_screen') img = photos.pick_image() if img: console.hud_alert('Please wait...') scale = scene.get_screen_scale() #print str(scale) picsize = scene.Size(*img.size) width = picsize[0] / scale height = picsize[1] / scale self.sv2 = self.view['scrollview2'] self.sv2.content_size = (width, height) self.sv2v1 = self.sv2.subviews[0] #sv2v1 = view1 in scrollview2 self.sv2v1.bounds = (0, 0, width, height) self.sceneView = scene.SceneView(frame=self.sv2v1.bounds) self.sceneView.scene = MyPicture(self.view['scrollview1'].subviews[0].text, img, picsize) img = None self.sv2.add_subview(self.sceneView) else: self.view.close()
def CombineScreens(): # Distance from left side of final image base = 0 # Pixels between screenshots in final image offset = 14 # Number of screenshots to combine total = 2 # iPhone 5 resolution height = 1136 width = (640 * total) + ((offset * total) - offset) # Create image background background = Image.new('RGB', (width, height), 'white') for i in range(total): screenshot = photos.pick_image(show_albums=True) if mode == 1: background.paste(screenshot, (base, 0)) elif mode == 2: cleanbar(screenshot) background.paste(screenshot, (base, 0)) base = base + screenshot.size[0] + offset background.show() # Upload to Dropbox folder from WorkPics import WorkPic WorkPic(background)
def CombineScreens(): # Distance from left side of final image base = 0 # Pixels between screenshots in final image offset = 14 # Number of screenshots to combine total = 2 # iPhone 5 resolution height= 1136 width = (640*total) + ((offset*total)-offset) # Create image background background = Image.new('RGB', (width,height), 'white') for i in range(total): screenshot = photos.pick_image(show_albums=True) if mode == 1: background.paste(screenshot,(base,0)) elif mode == 2: cleanbar(screenshot) background.paste(screenshot,(base,0)) base = base + screenshot.size[0] + offset background.show() # Upload to Dropbox folder from WorkPics import WorkPic WorkPic(background)
def do_GET(self): if os.path.splitext(self.path)[1] == '.html': self.send_response(200) self.send_header("Content-type", 'text/html') self.send_header("Last-Modified", self.date_time_string()) self.end_headers() self.wfile.write('<!DOCTYPE html><html><head><meta charset="utf-8"><script src="../ckeditor/ckeditor.js"></script></head><body><textarea cols="1" id="editor1" name="editor1" rows="1"></textarea><script>CKEDITOR.replace("editor1",{on: {}});</script></body></html>') elif os.path.splitext(self.path)[1] == '.jpg': try: bI = _gdI[self.path[1:]] except: with io.BytesIO() as bIO: ip = photos.pick_image(show_albums = True) ip.save(bIO, ip.format) bI = bIO.getvalue() _gdI[self.path[1:]] = bI self.send_response(200) self.send_header("Content-type", 'image/jpeg') self.send_header("Content-Length", str(len(bI))) self.send_header("Last-Modified", self.date_time_string()) self.end_headers() self.wfile.write(bI) else: SimpleHTTPRequestHandler.do_GET(self)
# https://gist.github.com/viticci/2e466ff4e6b3425aba3c import Image import photos import console import ImageOps # Pick screenshots to combine screenshot1 = photos.pick_image(show_albums=True) screenshot2 = photos.pick_image(show_albums=True) screenshot3 = photos.pick_image(show_albums=True) mode = console.alert('Create or Clean', 'Select a mode below.', 'Create Now', 'Clean First') if mode == 2: from Cleanbar import cleanbar cleanbar(screenshot1) cleanbar(screenshot2) cleanbar(screenshot3) # Creates final image console.clear() print "Creating final image..." background = Image.new('RGBA', (1850,1275), (255, 255, 255, 255)) file1 = screenshot1.resize((545,969),Image.ANTIALIAS) file2 = screenshot2.resize((700,1245),Image.ANTIALIAS) file3 = screenshot3.resize((545,969),Image.ANTIALIAS) file1 = ImageOps.expand(file1,border=1,fill='gray') file2 = ImageOps.expand(file2,border=1,fill='gray') file3 = ImageOps.expand(file3,border=1,fill='gray')
# https://forum.omz-software.com/topic/2353/encoding-images-in-base64 # coding: utf-8 import workflow import clipboard import photos import base64 source_selection = workflow.get_variable('source') if source_selection == 'photo': image_selection = photos.pick_image() else: image_selection = clipboard.get_image() if not image_selection: console.alert('No Image', 'Clipboard does not contain an image') w, h = image_selection.size encoded = base64.b64encode(str(image_selection) workflow.set_variable('encodedImage', str(encoded)) workflow.set_variable('origSize', str(w))
rot=ui.Button(frame=(self.startx-2*buttonsize-10,10,2*buttonsize,2*buttonsize)) rot.image=ui.Image.named('ionicons-ios7-refresh-empty-256') rot.action=self.rotate rot.tint_color=(0,0,0) self.add_subview(rot) self.buttonView = ui.View(frame=(self.startx, 0, buttonsize*16,buttonsize*16)) for x in range(16): for y in range(16): frame=(x*buttonsize,y*buttonsize,buttonsize,buttonsize) b=ui.Button(frame=frame) b.background_color=self.load[x,y] b.action=self.invert self.buttonView.add_subview(b) self.add_subview(self.buttonView) def draw(self): if not self.buttonView: self.makeButtons() def will_close(self): if __name__ == '__main__': self.finish() if __name__ == '__main__': import photos def show(image): image.show() MazeEditView(image=photos.pick_image(),finished_handler=show).present(hide_title_bar=1)
if g[j]<0: g[j] = g[j] - 0.5*quant u = iDCT(g,N) v = Opt(g,N,delta,C) naturalMat[i,:] = u optimalMat[i,:] = v return naturalMat, optimalMat # MAIN CODE C = 1 N = 8 quant = 2**4 #img = Image.open('sashaBig.png') img = photos.pick_image(True) I = img.convert('L') Img = array(I) original = zeros((len(Img),len(Img))) natural = zeros((len(Img),len(Img))) optimal = zeros((len(Img),len(Img))) for i in range(0,32): print i for j in range(0,32): img = Img[i*N:i*N+N,j*N:j*N+N] naturalMat, optimalMat = CompressBlock(img,C,N,quant) original[i*N:i*N+N,j*N:j*N+N] = Img[i*N:i*N+N,j*N:j*N+N] natural[i*N:i*N+N,j*N:j*N+N] = naturalMat optimal[i*N:i*N+N,j*N:j*N+N] = optimalMat
def run(self): img = photos.pick_image() return ElementValue(type = self.get_output_type(), value = img)
# coding: utf-8 # https://forum.omz-software.com/topic/2845/request-for-an-app/11 from PIL import Image import photos im = photos.pick_image() # Load the image with whatever method you'd like dimension = 1 if raw_input("Which dimension are you inputting?\n").lower() == "width" else 0 dimension_value = int(raw_input("Value: ")) """ We can use the proportion: image_width your_width ------------ = ----------------- image_height unknown_dimension and with this, cross-multiply""" if dimension: # We're solving for the height print im.size[1]*dimension_value / float(im.size[0]) else: print im.size[0]*dimension_value / float(im.size[1])
pth.stroke() # draw the path if len(drawpts) > 2: # 'close' the path to show area computed with ui.GState(): pth = ui.Path() pth.move_to(*drawpts[-1]) pth.line_to(*drawpts[0]) pth.set_line_dash([2, 3]) ui.set_color((1, .5, .5, .5)) pth.stroke() # create a 10 pixel circle at last entered point ui.Path.oval(drawpts[-1][0] - 5, drawpts[-1][1] - 5, 10, 10).fill() # show circles for previously entered points. smaller and lighter ui.set_color((1, .5, .5)) for p in drawpts[0:-1]: ui.Path.oval(p[0] - 3, p[1] - 3, 6, 6).fill() def polygonArea(X, Y, scale): '''compute scaled area of polygon,assuming it is closed ''' area = 0 j = len(X) - 1 for i in range(len(X)): area = area + (X[j] + X[i]) * (Y[j] - Y[i]) * scale**2 j = i return abs(area / 2) photos.pick_image().save("temp.jpg") v = RoomAreaView('temp.jpg') v.present('fullscreen')
import photos import console import Image def clear(): console.clear() console.set_font("Futura-Medium", 20) console.set_color(0.40, 0.40, 0.40) clear() print("Pick one image at a\ntime, when you're\ndone, tap anywhere\noutside the\npicker.") images = [] while 1: img = photos.pick_image(show_albums=True) if img: images.append(img) else: break count = len(images) clear() if count == 0: console.set_color(0.50, 0.00, 0.00) print("No images selected.") sys.exit() print("Merging {0} images...".format(count))
def imagepick(sender): im = photos.pick_image() if im: main(im) rootView.remove_subview(view1)
def pick_image(): data=photos.pick_image(raw_data=True) return data
def pick_photo(filename='.temp.jpg'): img = photos.pick_image() if img: img.save(filename) return filename
import photos class MyScene(Scene): def __init__(self, mapimage): mapimage2 = mapimage.convert('RGBA') self.mapimage = load_pil_image(mapimage2) super(MyScene, self).__init__() def draw(self): # This will be called for every frame background(1, 1, .5) fill(1, 0, 0) image(self.mapimage, 0, 0) # Draw a red circle for every finger that touches the screen: for touch in self.touches.values(): ellipse(touch.location.x - 50, touch.location.y - 50, 100, 100) mapimage = photos.pick_image(show_albums=True) if mapimage: scene = MyScene(mapimage) run(scene, frame_interval=1) mapimage2 = mapimage.convert('RGBA') mapimage.show() mapimage2.show() else: print 'Canceled or invalid image.'
p=ui.Path() p.move_to(*path[0]) for point in path: p.line_to(*point) p.line_join_style=ui.LINE_JOIN_ROUND p.line_cap_style=ui.LINE_CAP_ROUND p.line_width=buttonsize/4 return p def draw(self): self.buttonsize = int(self.height/16) self.startx=int((self.width/2-self.height/2)) buttonsize=self.buttonsize for x in range(16): for y in range(16): frame=(self.startx+x*buttonsize,y*buttonsize,buttonsize,buttonsize) p=ui.Path.rect(*frame) ui.set_color(self.load[x,y]) p.fill() path=self.Djk2UI(self.pathCalc()) ui.set_color((0,0,1)) ui.set_shadow((0,0,0),2,2,5) path.stroke() if __name__ == '__main__': SolutionView(photos.pick_image(), (1,0), (12,14)).present(hide_title_bar=1)