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 image_merge(img): if (img1_w * 1.0) / img1_h > 1: print 'Landscape screenshot...' #(2048, 1536) #Landscape screenshot background = Image.new('RGB', ((img1_w + 20), ((img1_h * 2) + 30)), (255, 255, 255)) print "Generating image..." background.paste(img1, (10, 10)) background.paste(img2, (10, (img1_h + 20))) # background.show() photos.save_image(background) print "Image saved" else: print 'Portrait screenshot...' #(1536, 2048) #Portrait screenshot background = Image.new('RGB', (((img1_w * 2) + 30), (img1_h + 20)), (255, 255, 255)) print "Generating image..." background.paste(img1, (10, 10)) background.paste(img2, ((img1_w + 20), 10)) # background.show() photos.save_image(background) print "Image saved"
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 SavePic(src): try: pic = Image.open(bio(requests.get(src).content)) photos.save_image(pic) print('Image saved.') except: print('Failed to save image.')
def save(self, sender): if self.pixel_editor.has_image(): image = self.pixel_editor.get_image() option = console.alert('Save Image', '', 'Camera Roll', 'New File', 'Copy image') if option == 1: photos.save_image(self.superview['preview'].image) console.hud_alert('Saved to cameraroll') elif option == 2: # Saves image to disk imageName = console.input_alert('Save Image') if imageName[-4:] == ".png": imageName = imageName[:-4] fileName = ('images/' + imageName + '.png') if isfile(fileName): console.hud_alert('File exist!','error') return False self.pixel_editor.imageName = imageName #name = 'images/image_{}.png' #get_num = lambda x=1: get_num(x+1) if isfile(name.format(x)) else x #file_name = name.format(get_num()) pixels_to_png(self.superview['editor'].background_color, self.pixel_editor.pixels, self.pixel_editor.row*2, self.pixel_editor.column, fileName) console.hud_alert('Image saved as "{}"'.format(fileName)) elif option == 3: clipboard.set_image(image, format='png') console.hud_alert('Copied') else: self.show_error()
def button_c_pressed(sender): global i global frame global filename i += 1 showpic = cv2.imwrite(filename+str(i)+'.png', frame) photos.save_image(showpic)
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 save_action(sender): global md if md.hd_img is None: return v['activity'].start() img = apply_filter_hd() photos.save_image(img) v['activity'].stop() log.warning('Image saved')
def pic_save(image, image_mode, width, height, quality, resize): print('\nPicture save is in process ...') if resize: image = image.resize((width, height), Image.ANTIALIAS) background = Image.new(image_mode, (width,height), 'white') background.paste(image, (0, 0)) clipboard.set_image((background), format='jpeg', jpeg_quality=quality) photos.save_image(clipboard.get_image()) fmt = 'Completed!\nResolution = {} x {}, quality = {:.0f}%, mode = {}' print(fmt.format(width, height, quality * 100, image_mode))
def save_action(self, sender): if self.image_view.image: # We draw a new image here, so that it has the current # orientation (the canvas is quadratic). with ui.ImageContext(self.width, self.height) as ctx: self.image_view.image.draw() img = ctx.get_image() photos.save_image(img) console.hud_alert('Saved') else: console.hud_alert('No Image', 'error')
def pic_save(image, width, height, text, font, fontsize, color, x, y, scale): background = Image.new('RGBA', (width,height), 'white') background.paste(image, (0, 0)) draw = ImageDraw.Draw(background) y = height - (y * scale) x = x * scale f = ImageFont.truetype(font, int(fontsize * scale)) textsize = draw.textsize(text, font=f) x -= textsize[0]/2 y -= ((textsize[1]/1.15)/2) # remove offset / add div factor 1.15 (difference between pixel size and font size) draw.text((x, y), text, font=f, fill=color) clipboard.set_image(background, format='jpeg', jpeg_quality=0.98) photos.save_image(clipboard.get_image())
def pic_save(image, width, height, text, font, fontsize, color, x, y, scale): background = Image.new('RGBA', (width,height), 'white') background.paste(image, (0, 0)) draw = ImageDraw.Draw(background) offset = fontsize / 3.2 # offset is relative to the fontsize fontsize *= scale y = height - y f = ImageFont.truetype(font, int(fontsize)) textsize = draw.textsize(text, font=f) x -= textsize[0]/2 y -= (textsize[1]/2) + offset draw.text((x, y), text, font=f, fill=color) clipboard.set_image(background, format='jpeg', jpeg_quality=0.98) photos.save_image(clipboard.get_image())
def run(self, input): try: if not photos.save_image(input.value): console.alert("didn't work") except error: console.alert('error: {}'.format(error)) self.status = 'complete'
def button_tapped(self, sender): pixel_editor = self.superview['editor'] if sender.name == 'trash': if console.alert('Trash', 'Are you sure you want to clear the pixel editor? Image will not be saved.', 'Yes'): pixel_editor.image_view.image = pixel_editor.reset() elif sender.name == 'save': if console.alert('Save Image', 'Save image to cameraroll?', 'Yes'): photos.save_image(pixel_editor.image_view.image) console.hud_alert('Saved to cameraroll') elif sender.name == 'undo': pixel_editor.undo() else: pixel_editor.mode = sender.name for b in self['tools'].subviews: b.background_color = tuple((0, 0, 0, 0)) sender.background_color = '#4C4C4C'
def save(sender): if photos.save_image(getpic(sender.superview.superview['canvas'])): sender.title = 'Saved' hud_alert('Saved') else: sender.title = 'Error' pass
def image_merge(img): if (img1_w*1.0)/img1_h > 1: print 'Landscape screenshot...' background = Image.new('RGB', ((img1_w+20), ((img1_h*2)+30)), (255,255,255)) print "Generating image..." background.paste(img1,(10,10)) background.paste(img2,(10,(img1_h+20))) photos.save_image(background) print "Image saved" else: print 'Portrait screenshot...' background = Image.new('RGB', (((img1_w*2)+30),(img1_h+20)), (255, 255, 255)) print "Generating image..." background.paste(img1,(10,10)) background.paste(img2,((img1_w+20),10)) photos.save_image(background) print "Image saved"
def main(): feed = feedparser.parse('http://nasa.gov/rss/dyn/lg_image_of_the_day.rss') latest = feed['entries'][0] title = latest['title'] description = latest['summary'] print '%s\n\n%s' % (title, description) links = latest['links'] image_url = None for link in links: if link.get('type').startswith('image'): image_url = link.get('href') if image_url: urllib.urlretrieve(image_url, 'ImageOfTheDay.jpg') img = Image.open('ImageOfTheDay.jpg') img.show() dialogs.alert('Save to Camera Roll?', title, 'Save') photos.save_image(img) dialogs.hud_alert('Image Saved')
def image_merge(img): if (img1_w * 1.0) / img1_h > 1: print('Landscape screenshot...') background = Image.new('RGB', ((img1_w + 20), ((img1_h * 2) + 30)), (255, 255, 255)) print("Generating image...") background.paste(img1, (10, 10)) background.paste(img2, (10, (img1_h + 20))) photos.save_image(background) print("Image saved") else: print('Portrait screenshot...') background = Image.new('RGB', (((img1_w * 2) + 30), (img1_h + 20)), (255, 255, 255)) print("Generating image...") background.paste(img1, (10, 10)) background.paste(img2, ((img1_w + 20), 10)) photos.save_image(background) print("Image saved")
def save(self, sender): if self.pixel_editor.has_image(): image = self.pixel_editor.get_image() option = console.alert('Save Image', '', 'Camera Roll', 'New File', 'Copy image') if option == 1: photos.save_image(image) console.hud_alert('Saved to cameraroll') elif option == 2: name = 'image_{}.png' get_num = lambda x=1: get_num(x+1) if os.path.isfile(name.format(x)) else x file_name = name.format(get_num()) with open(file_name, 'w') as f: ui_to_pil(image).save(f, 'png') console.hud_alert('Image saved as "{}"'.format(file_name)) elif option == 3: clipboard.set_image(image, format='png') console.hud_alert('Copied') else: self.show_error()
def image_merge(img): if (w*1.0)/h > 1: print 'Landscape screenshot...' #(2048, 1536) #Landscape screenshot background = Image.new('RGB', ((w+20), ((h*2)+30)), (255,255,255)) print "Generating image..." background.paste(im1,(10,10)) background.paste(im2,(10,(h+20))) # background.show() photos.save_image(background) else: print 'Portrait screenshot...' #(1536, 2048) #Portrait screenshot background = Image.new('RGB', (((w*2)+30),(h+20)), (255, 255, 255)) print "Generating image..." background.paste(im1,(10,10)) background.paste(im2,((w+20),10)) # background.show() photos.save_image(background)
def save(self, sender): if self.pixel_editor.has_image(): image = self.pixel_editor.get_image() option = console.alert('Save Image', '', 'Camera Roll', 'New File', 'Copy image') if option == 1: photos.save_image(image) console.hud_alert('Saved to cameraroll') elif option == 2: name = 'image_{}.png' get_num = lambda x=1: get_num(x + 1) if os.path.isfile( name.format(x)) else x file_name = name.format(get_num()) with open(file_name, 'w') as f: ui_to_pil(image).save(f, 'png') console.hud_alert('Image saved as "{}"'.format(file_name)) elif option == 3: clipboard.set_image(image, format='png') console.hud_alert('Copied') else: self.show_error()
def image_merge(img): if (w * 1.0) / h > 1: print('Landscape screenshot...') #(2048, 1536) #Landscape screenshot background = Image.new('RGB', ((w + 20), ((h * 2) + 30)), (255, 255, 255)) print("Generating image...") background.paste(im1, (10, 10)) background.paste(im2, (10, (h + 20))) # background.show() photos.save_image(background) else: print('Portrait screenshot...') #(1536, 2048) #Portrait screenshot background = Image.new('RGB', (((w * 2) + 30), (h + 20)), (255, 255, 255)) print("Generating image...") background.paste(im1, (10, 10)) background.paste(im2, ((w + 20), 10)) # background.show() photos.save_image(background)
def save_action(sender): scroll_view.close( ) # Close the view. Is this really the best place for this? chipsize = select_width / len(selected_colors) for i, c in enumerate(selected_colors): bar = (chipsize * i, select_height - chipsize, (chipsize * i) + chipsize, select_height) selected_image.paste(c, bar) selected_image.show() saveit = photos.save_image(selected_image) if saveit is True: console.hud_alert('Sampled image has been saved') elif saveit is False: console.hud_alert('Uh oh, not saved')
def touch_began(self, touch): sound.play_effect('Footstep') #creates a query of the locations recorded and opens it on google maps #because the query accepts at most around 20 points, if you have more #than 20 points it will create a new list and get points evenly spaced #throughout the path to a total of less than 20. Looks representative #and accurate. def mapView(self): googleMapsMaxPoints = 20 mapLocations = copy.deepcopy(self.locations) if len(self.locations) > googleMapsMaxPoints: mapLocations = [] jump = math.ceil(len(self.locations) / googleMapsMaxPoints) for i in range(0, len(self.locations), jump): mapLocations += [self.locations[i]] self.query = 'safari-https://www.google.com/maps/dir/' for loc in mapLocations: self.query += str(loc[0]) self.query += "," self.query += str(loc[1]) self.query += "/" self.query = self.query[:-1] webbrowser.open(self.query) #when you run across a landmark (photo) you placed down, it will #notify you its present and you can tap to reveal the photo def openLandmark(self): sound.play_effect('Click_1') self.imageModeOpen = True self.imageMode = False self.heightPhoto = (self.photoHeight/self.photoWidth) * \ (self.size.x-20) self.widthPhoto = (self.photoWidth/self.photoWidth) * \ (self.size.x-20) self.heightFrame = self.heightPhoto + 10 self.widthFrame = self.widthPhoto + 10 self.halfScreenFrame = self.size.y / 2 - self.heightFrame / 2 self.halfScreen = self.size.y / 2 - self.heightPhoto / 2 #asked a question on the omz (Pythonista) forum and they answered! #'https://forum.omz-software.com/topic/5263/displaying-an-image- #from-album-in-photos-onto-screen-in-scene-module' #opens the image and has it hidden. self.img = ui.Button(name='image') self.img.frame = (10, self.halfScreen, self.widthPhoto, self.heightPhoto) self.img.background_image = self.ui_image self.img.enable = False self.img.hidden = False self.view.add_subview(self.img) #when you tap, get the current location to perform functions current = location.get_location() #solved the close points problem using rounding latLong = (round(current['latitude'], 4), round(current['longitude'], 4)) picTaken = latLong in self.photoLocations #get the location on the screen of the touch x, y = touch.location #if the image is open, close it when you tap (has to be off the image) if self.imageModeOpen == True: self.imageModeOpen = False self.img.hidden = True #if you have the loop Prompt, you must tap an answer in order to use #the other functions if self.loopPrompt == True: if x > 50 and x < self.size.x/2 and y < self.size.y/2 \ and y > self.size.y/2 - 50: self.loopPrompt = False self.loopPromptState = 1 elif x > self.size.x/2 and x < self.size.x-50 \ and y < self.size.y/2 and y > self.size.y/2 - 50: self.loopPrompt = False self.loopPromptState = 2 #when it has the more menu open, you must are not able to tap any of #the other buttons, other than the ones in the more menu elif self.MoreState == True: #SOS State tap, call the cops if you tap if x < self.size.w/2 + 30 and x > self.size.w/2 - 30 \ and y > 50 and y < 100 and self.MoreState == True: webbrowser.open('tel:911') #MapView tap elif x < 100 and x > 50 and y < 220 and y > 160 and \ len(self.locations) >= 2: mapView(self) #create the query, but make it a link for phone users, and copy #it to the clipboard elif x < self.size.x/2+40 and x > self.size.x/2-40 and \ y < 220 and y > 160 and len(self.locations) >= 2: googleMapsMaxPoints = 20 mapLocations = copy.deepcopy(self.locations) if len(self.locations) > googleMapsMaxPoints: mapLocations = [] jump = math.ceil(len(self.locations) / googleMapsMaxPoints) for i in range(0, len(self.locations), jump): mapLocations += [self.locations[i]] self.query = 'safari-https://www.google.com/maps/dir/' for loc in mapLocations: self.query += str(loc[0]) self.query += "," self.query += str(loc[1]) self.query += "/" self.query = self.query[:-1] clipboard.set(self.query[7:]) self.clipState = True #tap on Trace button to reveal the path elif x < self.size.x-50 and x > self.size.x-100 and y < 220 \ and y > 160 and len(self.locations) > 2: self.pathState = True #tap on theme button to switch the theme elif x < self.size.w/2 + 30 and x > self.size.w/2 - 30 \ and y > self.size.y-95-40 and y < self.size.y-95+40: self.themeSwitch += 1 if self.themeSwitch % 2 == 0: self.theme = self.lightMode elif self.themeSwitch % 2 == 1: self.theme = self.darkMode #tap off a button while in the more menu, and it exits the menu else: self.MoreState = False self.clipState = False self.pathState = False #open landmark by tapping on the banner elif y > 150 and y < 200 and self.imageMode == True: openLandmark(self) #if in image mode, tap off the image to get rid of it off the screen elif y < 150 and y > 200 and self.imageMode == True: self.imageMode = False #reset button resets everything elif x < 100 and x > 50 and y < 100 and y > 50: self.measuringOn = False self.functionState = 0 self.background_color = self.theme["backgroundColor"] self.locations = [] self.needMore = False self.photoCount = 0 self.photoLocations = [] self.locationsLeft = [] self.needMore = False self.timerCount = 0 #more button is a small and out of the way, opens up more menu elif x < self.size.w/2 + 25 and x > self.size.w/2 - 25 and y < 30 \ and y > 0: self.MoreState = True #take photos and add to album elif x < self.size.w/2 + 30 and x > self.size.w/2 - 30 \ and y > 50 and y < 100 and self.MoreState == False and \ self.measuringOn == True and picTaken == False: imageree = photos.capture_image() if imageree != None: #open up the camera and you can take photo photos.save_image(imageree) time.sleep(1) self.photoCount += 1 allAssets = photos.get_assets() theImage = allAssets[-1] #if there is no album, create album 'Thread' try: self.photoLibrary = [a for a in photos.get_albums() \ if a.title == 'Thread'][0] except IndexError: self.photoLibrary = photos.create_album('Thread') #add the image to the album for the user to have and for #future use in the app's use (landmarks!) theImage = allAssets[len(allAssets) - 1] self.photoLibrary.add_assets([theImage]) self.photoLocations += [latLong] #compass State: Letters (NWSE) or degrees elif x < 325 and x > 275 and y < 100 and y > 50: self.compassStat = not (self.compassStat) #go to measuring mode when tapped for the first time elif self.measuringOn == False and self.functionState == 0: self.measuringOn = True self.background_color = self.theme["backgroundColor"] self.functionState += 1 #if you need more values do not let the user stop recording elif self.measuringOn == True and self.functionState == 1 \ and len(self.locations) < 4: self.needMore = True #if you have enough locations, when you tap you can move to next state elif self.measuringOn == True and self.functionState == 1 \ and len(self.locations) > 3: #sound.play_effect('arcade:Laser_1') self.needMore = False self.measuringOn = False self.background_color = self.theme["backgroundColor"] self.functionState += 1 #move function state up to state 4 so you can begin tracing back elif self.measuringOn == False and self.functionState == 3: #sound.play_effect('arcade:Laser_1') self.background_color = self.theme["backgroundColor"] self.functionState += 1
import photos import Image choose = photos.pick_image() final = choose.resize((800, 600), Image.ANTIALIAS) saveit = photos.save_image(final) if saveit is True: print 'Resized image has been saved' elif saveit is False: print "Uh oh, not saved"
# coding: utf-8 ## Resize an image (either from external apps' share-sheet, or via photo-roll) import photos, appex, sys, console if appex.is_running_extension(): im = appex.get_image() else: im = photos.pick_image() if im is None: console.hud_alert("No image chosen", "error", 1.0) sys.exit(0) else: assert str(type(im))[8:-2][4:].partition("ImagePlugin")[0] in ("Bmp", "Gif", "Jpeg", "Png", "Ppm", "Tiff") width, height = im.size percentage = int(console.input_alert("Resize image to _%", "Enter number")) fraction = percentage / 100.0 new_width = int(round(width*float(fraction))) new_height = int(round(height*float(fraction))) im2 = im.resize((new_width, new_height)) saved = photos.save_image(im2) if saved: console.hud_alert("Successfully saved resized image ({0}%)".format(int(percentage))) else: console.hud_alert("Unsuccessfully saved resized image ({0}%)".format(int(percentage)), "error")
from PIL import Image import photos import console image = photos.pick_image(original=False) def customSize(image): w, h = image.size print('Original image size: {} x {} pixels\n'.format(w, h)) if w > 1200: wsize = 1200 / float(w) hsize = int(float(h) * float(wsize)) image = image.resize((1200, hsize), Image.ANTIALIAS) print 'Modified image size: 1200 × ' + str(hsize) + ' pixels' else: print 'Image is too small to be resampled. Width is less than 1200 pixels' return image image = customSize(image) image.show() saveit = photos.save_image(image) print '\n' + 'Done!' + '\n'
resizeAmountQ = console.alert('What percent of original size?','',q1,q2,'Custom') if resizeAmountQ == 1 : resizeAmount = float(q1[0:2]) / 100 elif resizeAmountQ == 2 : resizeAmount = float(q2[0:2]) / 100 elif resizeAmountQ == 3 : resizeAmount = float(console.input_alert('What percent of original size?','Number only','40')) / 100 else: print 'Whups!' exit while True: img = clipboard.get_image(idx=x) if img: width, height = img.size smaller = img.resize( (int(width * resizeAmount), int(height * resizeAmount) ), Image.ANTIALIAS) photos.save_image(smaller) x += 1 elif x == 0 : print 'No images found on the clipboard.' else: print 'Looks like it worked. The downsampled images should be in your camera roll.' break
import photos import Image choose = photos.pick_image() final = choose.resize((800,600),Image.ANTIALIAS) saveit = photos.save_image(final) if saveit is True: print 'Resized image has been saved' elif saveit is False: print "Uh oh, not saved"
from PIL import Image, ImageOps import clipboard, photos,webbrowser im=photos.pick_image()#clipboard.get_image if im.size[0] >= im.size[1]: whitespace=((im.size[0]-im.size[1])/2)+250 xbump=250 else: xbump=((im.size[1]-im.size[0])/2)+250 whitespace=250 matted=ImageOps.expand(im,border=(xbump,whitespace),fill='white') photos.save_image(matted) inst='instagram://camera' webbrowser.open(inst) #if you have any questions or comments @jamescampbell on twitter
def saveLibrary_action(sender): if sender.superview['imageview1'].image is None: hud_alert('No image to save', icon='error') return photos.save_image(sender.superview['imageview1'].image) hud_alert('Saved')
def take_photo_action(self, sender): image = photos.capture_image() photos.save_image(image)
import clipboard import urllib import Image import photos import cStringIO # Given an image URL in the clipboard, save the image to the iOS Camera Roll with Pythonista. Simple script with no error checks or other settings. URL = clipboard.get() file = Image.open(cStringIO.StringIO(urllib.urlopen(URL).read())) photos.save_image(file) print 'Image Saved'
""" This code takes two screenshots from the camera roll combines them into one image and saves the new image to the camera roll. This is adapted from Federico Viticci's blog post at: http://www.macstories.net/stories/automating-ios-how-pythonista-changed-my-workflow/ It removes the option to change which picture is where, automatically assigning the first one chosen as the leftmost image. It also removes the necessity to copy the images to the clipboard outside of Pythonista using the new photos library in version 1.3. Finally, it removes the clipboard output. """ from __future__ import print_function import photos import Image import console im1 = photos.pick_image(show_albums=False) im2 = photos.pick_image(show_albums=False) background = Image.new('RGBA', (746, 650), (255, 255, 255, 255)) console.clear() print("Generating image...") console.show_activity() _1 = im1.resize((366, 650), Image.ANTIALIAS) _2 = im2.resize((366, 650), Image.ANTIALIAS) background.paste(_1, (0, 0)) background.paste(_2, (380, 0)) photos.save_image(background) console.hide_activity() print("Image saved to camera roll.")
Image.FLIP_LEFT_RIGHT), (Image.ROTATE_90, Image.FLIP_LEFT_RIGHT), (Image.ROTATE_270, None), (Image.ROTATE_270, Image.FLIP_LEFT_RIGHT), (Image.ROTATE_90, None))[o - 1] if not (f is None): img = img.transpose(f) if not (r is None): img = img.transpose(r) width, height = img.size #Prompt for new width and height. width2 = adjust( width, console.input_alert("Width", "Enter new image width.", str(width))) height = int(height * (float(width2) / width)) height2 = adjust( height, console.input_alert("Height", "Enter new image height.", str(height))) #Scale and save new image. img = img.resize((width2, height2), Image.ANTIALIAS) if photos.save_image(img): msg = "Saved." else: msg = "Save failed." console.alert(msg, button1="OK", hide_cancel_button=True)
# http://soitscometothis.net/Create-side-by-side-screen-shots-on-iOS-with-Pythonista/ # https://gist.github.com/nuclearzenfire/5090763 """ This code takes two screenshots from the camera roll combines them into one image and saves the new image to the camera roll. This is adapted from Federico Viticci's blog post at: http://www.macstories.net/stories/automating-ios-how-pythonista-changed-my-workflow/ It removes the option to change which picture is where, automatically assigning the first one chosen as the leftmost image. It also removes the necessity to copy the images to the clipboard outside of Pythonista using the new photos library in version 1.3. Finally, it removes the clipboard output. """ import photos import Image import console im1 = photos.pick_image(show_albums=False) im2 = photos.pick_image(show_albums=False) background = Image.new('RGBA', (746,650), (255, 255, 255, 255)) console.clear() print "Generating image..." console.show_activity() _1 = im1.resize((366,650),Image.ANTIALIAS) _2 = im2.resize((366,650),Image.ANTIALIAS) background.paste(_1,(0,0)) background.paste(_2,(380,0)) photos.save_image(background) console.hide_activity() print "Image saved to camera roll."
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 print ('Error of natural method:', linalg.norm(original-natural)) print ('Error of optimal method:', linalg.norm(original-optimal)) #original = toImage(original) #photos.save_image(original) #original.save('original.png') natural = toImage(natural) photos.save_image(natural) #natural.save('natural.png') optimal = toImage(optimal) photos.save_image(optimal) #optimal.save('optimal.png')
'{0}% (default for {1})'.format(reduction_amounts[q2], q2), 'Custom') if resizeAmountQ == 1: resizeAmount = float(reduction_amounts[q1]) / 100 elif resizeAmountQ == 2: resizeAmount = float(reduction_amounts[q2]) / 100 elif resizeAmountQ == 3: resizeAmount = float( console.input_alert('What percent of original size?', 'Number only', '40')) / 100 else: print 'Whups!' sys.exit() x = 0 while True: img = clipboard.get_image(idx=x) if img: width, height = img.size smaller = img.resize( (int(width * resizeAmount), int(height * resizeAmount)), Image.ANTIALIAS) photos.save_image(smaller) x += 1 else: print 'Looks like it worked. The downsampled images should be in your camera roll.' break
# ipa フォントは StaSh を使って wget してきて unzip font = ImageFont.truetype( '/private/var/mobile/Containers/Shared/AppGroup/たぶんここがそれぞれの端末で違う/Pythonista3/Documents/ipag.ttf', 100) # 上の行は端末だけでなく、インストールするたびにユニークなものになるらしいので入れ直した時などは修正が必要 # 座標は(横,縦)で指定 drawbuffer.text((20, 20), 'from Pythonista app @tenyawanya', fill='red', font=font) # 他の画像を重ねたい時は以下をアンコメントして使ってる #img2= Image.open('re2.png', 'r') #img1.paste(img2, (680, 400), img2.split()[3]) # 撮影した画像をそのまま保存する場合はアンコメント #saveit = photos.save_image(img1) #img1.show() # ここまで # 正方形の画像として保存したい場合 crop_img = img1.resize((0, 0, 3024, 3024)) saveit = photos.save_image(crop_img) crop_img.show() # ここまで if saveit_re is True: print("saved") # 保存した画像をそのままインスタに投稿したいので以下を追加 insta = 'instagram://camera' webbrowser.open(insta)
# -*- coding: utf-8 -*- from PIL import Image from PIL import ImageDraw import photos #img1 = photos.pick_image() img1 = photos.capture_image() img1.convert('RGBA') drawbuffer = ImageDraw.Draw(img1) img2 = Image.open('kinoco.jpg') img1.paste(img2, (-102, 648)) img1.show() saveimg = photos.save_image(img1) if saveimg is True: print("saved")
images = [] number_of_images = int(dialogs.input_alert("# of images?")) assert 1 <= number_of_images <=36 i = 0 while i < number_of_images: images.append(photos.pick_image()) i += 1 widths, heights = zip(*(j.size for j in images)) total_width = sum(widths) max_height = max(heights) new_image = Image.new("RGB", (total_width, max_height)) x_offset = 0 for im in images: new_image.paste(im, (x_offset, 0)) x_offset += im.size[0] try: photos.save_image(new_image) dialogs.hud_alert("Saved!") new_image.show() except Exception: dialogs.hud_alert("could not save file!".title(), "error") sys.exit(0)
def touch_began(self, touch): current = location.get_location() latLong = (round(current['latitude'], 4), round(current['longitude'], 4) ) #solved the close points problem using rounding picTaken = latLong in self.photoLocations x, y = touch.location if self.imageModeOpen == True: self.imageModeOpen = False self.img.hidden = True if self.loopPrompt == True: if x > 50 and x < self.size.x / 2 and y < self.size.y / 2 and y > self.size.y / 2 - 50: self.loopPrompt = False self.loopPromptState = 1 elif x > self.size.x / 2 and x < self.size.x - 50 and y < self.size.y / 2 and y > self.size.y / 2 - 50: self.loopPrompt = False self.loopPromptState = 2 elif self.MoreState == True: #SOS State if x < self.size.w / 2 + 30 and x > self.size.w / 2 - 30 and y > 50 and y < 100 and self.MoreState == True: webbrowser.open('tel:911') #MapView elif x < 100 and x > 50 and y < 220 and y > 160 and len( self.locations) >= 2: googleMapsMaxPoints = 20 mapLocations = copy.deepcopy(self.locations) if len(self.locations) > googleMapsMaxPoints: mapLocations = [] jump = math.ceil(len(self.locations) / googleMapsMaxPoints) for i in range(0, len(self.locations), jump): mapLocations += [self.locations[i]] self.query = 'safari-https://www.google.com/maps/dir/' for loc in mapLocations: self.query += str(loc[0]) self.query += "," self.query += str(loc[1]) self.query += "/" self.query = self.query[:-1] webbrowser.open(self.query) elif x < self.size.x / 2 + 40 and x > self.size.x / 2 - 40 and y < 220 and y > 160 and len( self.locations) >= 2: googleMapsMaxPoints = 20 mapLocations = copy.deepcopy(self.locations) if len(self.locations) > googleMapsMaxPoints: mapLocations = [] jump = math.ceil(len(self.locations) / googleMapsMaxPoints) for i in range(0, len(self.locations), jump): mapLocations += [self.locations[i]] self.query = 'safari-https://www.google.com/maps/dir/' for loc in mapLocations: self.query += str(loc[0]) self.query += "," self.query += str(loc[1]) self.query += "/" self.query = self.query[:-1] clipboard.set(self.query[7:]) self.clipState = True elif x < self.size.x - 50 and x > self.size.x - 100 and y < 220 and y > 160 and len( self.locations) > 2: self.pathState = True else: self.MoreState = False self.clipState = False self.pathState = False #open landmark elif y > 150 and y < 200 and self.imageMode == True: sound.play_effect('arcade:Laser_2') self.imageModeOpen = True self.imageMode = False self.heightFrame = (self.photoHeight / self.photoWidth) * (self.size.x) self.widthFrame = (self.photoWidth / self.photoWidth) * (self.size.x) self.heightPhoto = (self.photoHeight / self.photoWidth) * (self.size.x - 20) self.widthPhoto = (self.photoWidth / self.photoWidth) * (self.size.x - 20) self.halfScreenFrame = self.size.y / 2 - self.heightFrame / 2 self.halfScreen = self.size.y / 2 - self.heightPhoto / 2 self.img = ui.Button(name='image') self.img.frame = (10, self.halfScreen, self.widthPhoto, self.heightPhoto) self.img.background_image = self.ui_image self.img.enable = False self.img.hidden = False self.view.add_subview(self.img) elif y < 150 and y > 200 and self.imageMode == True: self.imageMode = False #reset button elif x < 100 and x > 50 and y < 100 and y > 50: self.measuringOn = False self.checkedOnce = 0 self.background_color = self.theme["backgroundColor"] self.locations = [] self.needMore = False self.photoCount = 0 self.photoLocations = [] self.locationsLeft = [] self.needMore = False self.timerCount = 0 #more button elif x < self.size.w / 2 + 25 and x > self.size.w / 2 - 25 and y < 30 and y > 0: self.MoreState = True #take photos and add to album elif x < self.size.w / 2 + 30 and x > self.size.w / 2 - 30 and y > 50 and y < 100 and self.MoreState == False and self.measuringOn == True and picTaken == False: imageree = photos.capture_image() if imageree != None: photos.save_image(imageree) time.sleep(1) self.photoCount += 1 allAssets = photos.get_assets() theImage = allAssets[-1] #print("Divider") # Find the album or create it: try: self.photoLibrary = [ a for a in photos.get_albums() if a.title == 'Thread' ][0] except IndexError: self.photoLibrary = photos.create_album('Thread') # Add the file as an asset to the library: # asset = photos.create_image_asset(theImage) # Add the asset to the album: theImage = allAssets[len(allAssets) - 1] self.photoLibrary.add_assets([theImage]) self.photoLocations += [latLong] #compass State: Letters (NWSE) or degrees elif x < 325 and x > 275 and y < 100 and y > 50: self.compassStat = not (self.compassStat) elif self.measuringOn == False and self.checkedOnce == 0: #sound.play_effect('arcade:Laser_2') self.measuringOn = True self.background_color = self.theme["backgroundColor"] self.checkedOnce += 1 elif self.measuringOn == True and self.checkedOnce == 1 and len( self.locations) < 4: #sound.play_effect('arcade:Laser_1') self.needMore = True elif self.measuringOn == True and self.checkedOnce == 1 and len( self.locations) > 3: #sound.play_effect('arcade:Laser_1') self.needMore = False self.measuringOn = False self.background_color = self.theme["backgroundColor"] self.checkedOnce += 1 elif self.measuringOn == False and self.checkedOnce == 3: #sound.play_effect('arcade:Laser_1') self.background_color = self.theme["backgroundColor"] self.checkedOnce += 1
def resize_and_watermark(self, watermark): # Open a source file. source_origin, source_file_date = self.__get_image() # for PC debug. # source_file_date = datetime.today() # source_origin = Image.open('../images/IMG_3511.jpg') if source_origin is None: return None, None, None # Get a creation time. watermark_text = self.__get_watermark(source_origin, watermark, source_file_date) print(watermark_text) # Fit to instagram. mount_rightbottom = (0, 0) # counvert source_origin from RGB to ARGB. image_object = source_origin.convert('RGBA') if watermark.format == 1: source_background, mount_rightbottom = self.__fit_to_instagram_square_mount( image_object) else: source_background = self.__fit_to_instagram(image_object) # Generate a watermark image. watermark_image = Image.new('RGBA', source_background.size, (255, 255, 255, 0)) watermark_image_draw_object = ImageDraw.Draw(watermark_image) # Get a font font = ImageFont.truetype(font=watermark.font_style, size=watermark.font_size) # Get a text size text_width, text_height = watermark_image_draw_object.textsize( watermark_text, font=font) # Get a position position = (0, 0) if watermark.format == 1 and mount_rightbottom is not None: position = (mount_rightbottom[0] - text_width - 5, mount_rightbottom[1]) else: position = self.__get_watermark_position(source_background.width, source_background.height, text_width, text_height, watermark) # Get the color different from the color of the rear image plt, optimisation_color = self.__get_watermark_color( source_background, position, text_width, text_height) watermark.color = (optimisation_color, optimisation_color, optimisation_color) # Draw a text watermark_image_draw_object.text(position, watermark_text, font=font, fill=watermark.color + (watermark.opacity, )) # Composite a images. out = Image.alpha_composite(source_background, watermark_image).convert('RGB') # Save a image file. photos.save_image(out) # for PC debug. # out.show() # out.save("../output/out.jpg") sign = out.crop((position[0], position[1], position[0] + text_width, position[1] + text_height)) return out, sign, plt