コード例 #1
0
    def btn_save(self, sender):
        print('btn_save')
        saveimage0 = self.ui2pil(self.biv.image)

        nitiji_now = datetime.datetime.now()  # 現在日時の取得
        file_nitiji = nitiji_now.strftime(
            "%Y%m%d_%H%M%S")  #pillowはファイル名に全角は使えない。
        # datetime関数から日時を取り出して、表示する文字の変数に代入。ファイル名にいきなり入れると処理落ちする事がある
        filename = file_nitiji + '.jpg'
        print(str(self.image_w) + ' , ' + str(self.image_h))
        #pil risize int必須。ANTIALIASは、性能重視で遅い。
        saveimage = saveimage0.resize((int(self.image_w), int(self.image_h)),
                                      Image.ANTIALIAS)  #for PIL
        #zoom関係なく、xy各々2倍になるので、元のサイズに縮小している。
        saveimage.save(filename, quality=95, optimize=True,
                       progressive=True)  #for PIL
        # カメラロールに保存する前にpyのフォルダに画像を保存する必要がある。
        filename2 = 'MemoCamera' + str(
            self.filename1) + str(file_nitiji) + 'Draw.jpg'
        #filename1=nyuuryoubunn クラス呼出時のコンストラクタに追加した引数
        os.rename(filename, filename2)  #pillowの代わりに全角ファイル名を作成
        #print('Draw_filename2:',filename2)
        photos.create_image_asset(filename2)  # カメラロールへの保存。
        # ファイル名は以前に保存した画像ファイルへのパス。保存名ではない。

        #file deleate
        os.remove(filename2)
        # pyフォルダに生成されたJPEGを消さないと、最初のファイルのタイムスタンプが
        # 写真のexifデータに継承され続ける為、pyフォルダのjpgは毎回消す。
        #titleに画像サイズと倍率を表示
        self.name = 'save success'
コード例 #2
0
 def save_button_action(self, sender):
     path = 'temp.jpg'
     with ui.ImageContext(self.width, self.height) as ctx:
         self.draw_snapshot()  # draw entire view
         ui_image = ctx.get_image()
     pil = Image.open(io.BytesIO(ui_image.to_png()))
     x_min = 9999
     y_min = 9999
     x_max = 0
     y_max = 0
     for s in self.subviews:
         if 'Photo' in s.name:
             if s.x < x_min:
                 x_min = int(s.x)
             if s.y < y_min:
                 y_min = int(s.y)
             if (s.x + s.width - 1) > x_max:
                 x_max = int(s.x + s.width - 1)
             if (s.y + s.height - 1) > y_max:
                 y_max = int(s.y + s.height - 1)
     crop_pil = pil.crop((x_min * 2, y_min * 2, x_max * 2, y_max * 2))
     crop_pil.save(path, quality=95)
     photos.create_image_asset(path)
     os.remove(path)
     self.saved = True
コード例 #3
0
ファイル: mpv.py プロジェクト: dbdoer/PyEhViewer
 def save_picture(self, sender):
     pic_path = self._get_pic_path(self.infos['pics'][self.page]['img_id'])
     if pic_path != 'loading.jpg':
         photos.create_image_asset(pic_path)
         console.hud_alert('已保存')
     else:
         console.hud_alert('此图片不存在', 'error')
コード例 #4
0
def gen_text(filename, dict):  #takes in dictionary of titles and values
    w = 600
    h = 60
    filename = "./Render/" + str(filename) + "_Text.png"
    img = Image.new('RGBA', (w, h), (255, 0, 0, 0))
    fnt = ImageFont.truetype('./Icons/Arial.ttf', 30)
    d = ImageDraw.Draw(img)

    shoe_print = Image.open("./Icons/shoe-print.png")
    timer = Image.open("./Icons/timer.png")
    speedometer = Image.open("./Icons/speedometer.png")

    #x,y
    row_1 = 10
    row_2 = 15

    d.text((60, row_2),
           str(dict['distance_miles']),
           font=fnt,
           fill=(255, 255, 255))
    d.text((260, row_2), str(dict['elapsed']), font=fnt, fill=(255, 255, 255))
    d.text((460, row_2), str(dict['pace']), font=fnt, fill=(255, 255, 255))

    img.save(filename)
    d = Image.open(filename)

    d.paste(shoe_print, (0, row_1), shoe_print)
    d.paste(timer, (200, row_1), timer)
    d.paste(speedometer, (400, row_1), speedometer)

    d.save(filename)
    photos.create_image_asset(filename)  #ios
コード例 #5
0
def save_to_photo_app():
    img_dir = './downloads' 
    img_files = glob(os.path.join(img_dir, '*'))

    for img_file in img_files:
        if img_file.split('.')[-1] == 'jpg':
            photos.create_image_asset(img_file) 
            os.remove(img_file)
コード例 #6
0
def main():
	
	"""
	Script for iOS share extensions in Photos app to remove EXIF data from image when shared. Original image is preserved. Image with no EXIF is saved as JPEG to camera roll with creation date and time as filename.
	
	Requires piexif. Add piexif to the site_packages_3 folder or use stash to use pip
	"""
	
	if not appex.is_running_extension():
		print("This extension is designed to work with iOS share functionality, select and share photos from the Photos app")
	else:
		img = appex.get_image(image_type="pil")
		
	if img:
		
		if "exif" in img.info:
			
			exif_dict = piexif.load(img.info["exif"])
			
			if piexif.ImageIFD.Orientation in exif_dict["0th"]:
				orientation = exif_dict["0th"][piexif.ImageIFD.Orientation]
				
			if piexif.ExifIFD.DateTimeOriginal in exif_dict["Exif"]:
				date_time = exif_dict["Exif"][piexif.ExifIFD.DateTimeOriginal]
				
			path = date_time.decode("utf-8").replace(' ', '')
			path = path.replace(':', '')
			path = f"{path}.jpg"
			
		else:
			path = "web_image.jpg"
			print('No EXIF data')
			
		if orientation == 2:
			img = img.transpose(Image.FLIP_LEFT_RIGHT)
		elif orientation == 3:
			img = img.rotate(180)
		elif orientation == 4:
			img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
		elif orientation == 5:
			img = img.rotate(-90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
		elif orientation == 6:
			img = img.rotate(-90, expand=True)
		elif orientation == 7:
			img = img.rotate(90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
		elif orientation == 8:
			img = img.rotate(90, expand=True)
			
		img.save(path, quality = 95)
		photos.create_image_asset(path)
		os.remove(path)

	else:
		print('No input image found')
コード例 #7
0
    def _take_photo(self,size):
        while size == self._que.qsize():
            pass
        self.whiteWaiter.submit(self._whiteWaiter)
        self.savingPhotoView.alpha = 0.5

        # motion.start_updates()
        motionData = motion.get_gravity()
        # motion.stop_updates()

        if motionData[0] >= 0.5:
            rot = 1
        elif motionData[0] <= -0.5:
            rot = 0
        else:
            rot = 3
        # delta = time.time() - self.shoot
        # print('shooted time:{}'.format(delta))
        ciimage = self._que.get()

        uiImg = UIImage.imageWithCIImage_scale_orientation_(
            ciimage, 1.0, rot)

        if self._fileformat == 'PNG':
            data = ObjCInstance(c.UIImagePNGRepresentation(uiImg.ptr))
            fmt = 'png'
        elif self._fileformat == 'CIImage':
            data = uiImg.CIImage()
        elif self._fileformat == 'UIImage':
            data = uiImg
        else:
            quality = 0.8
            data = ObjCInstance(
                c.UIImageJPEGRepresentation(uiImg.ptr, quality))
            fmt = 'jpg'

        if self._saveAlbum:
            temppath = self._saveData2temp(data,fmt)
            photos.create_image_asset(temppath)

        if self._fileformat == 'PIL':
            temppath = self._saveData2temp(data,'pil')
            data = self._temp2pil(temppath)
            
        self._que.task_done()
        
        if self._autoclose:
            self.data = data
            time.sleep(1)
            self.close()
        
        if self._que.all_tasks_done:
            self.latestPhotoView.image = self._get_latest_photo_from_path(temppath)
            self.savingPhotoView.alpha = 0.0
コード例 #8
0
def addImagefileToAlbum(imagefilePath, albumName):
    try:
        album = [a for a in photos.get_albums() if a.title == albumName][0]
    except IndexError:
        album = photos.create_album(albumName)
    asset = photos.create_image_asset(imagefilePath)
    album.add_assets([asset])
コード例 #9
0
    def image_to_asset(self, image, batch=False):
        """
        Convert image (file) to Pythonista Image Asset        
        """

        # Check if it's already an asset
        if isinstance(image, photos.Asset):
            return image

        # It's not already an asset, lets convert it.
        try:
            return photos.create_image_asset(image)
        except FileNotFoundError:
            if batch:
                self.errors.append('Error: File {} not found.'.format(image))
            else:
                self._alert_error('File Not Found')
        except PermissionError:
            if batch:
                self.errors.append('Unable to access image {}, Access is Denied. \n' \
                                   'If issue persists restart Pythonista.'.format(image))
            else:
                self._alert_error(
                    'Unable to access image, Access is Denied. If issue persists restart Pythonista.'
                )
        except Exception as e:
            raise e

        return False
コード例 #10
0
def add_to_album(image_path, album_name):
    try:
        album = [a for a in photos.get_albums() if a.title == album_name][0]
    except IndexError:
        album = photos.create_album(album_name)
    asset = photos.create_image_asset(image_path)
    album.add_assets([asset])
    os.remove(image_path)
コード例 #11
0
def save2Album(image_files):
	album_name = 'pythonEx'
	printEx('Save to Album: %s' % album_name)
	asset_collections = getAlbum(album_name)
	assets = []
	for f in image_files:
		_asset = photos.create_image_asset(f)
		assets.append(_asset)
	asset_collections.add_assets(assets)
コード例 #12
0
def crop_all(L):
    try:
        for asset in L:
            # get the original(True) image of the asset, crop it by the imagers bounding box and show it.
            asset.get_image(True).crop(asset.get_image(True).getbbox()).show()
            cropped.append(
                asset.get_image(True).crop(asset.get_image(True).getbbox()))
            converted.append(photos.create_image_asset(asset))
        #album.add _assets(L)
    except:
        None
コード例 #13
0
def add_to_album(image_path, album_name):
    # KUDOS to Ole Zorn here!
    # Source: https://forum.omz-software.com/topic/3889/adding-an-image-to-my-own-album-in-photos-how/2
    # Find the album or create it:
    try:
        album = [a for a in photos.get_albums() if a.title == album_name][0]
    except IndexError:
        album = photos.create_album(album_name)
    # Add the file as an asset to the library:
    asset = photos.create_image_asset(image_path)
    # Workaround a possible timestamp bug:
    asset.creation_date = datetime.datetime.now()
    # Add the asset to the album:
    album.add_assets([asset])
コード例 #14
0
def run_and_graph(color_choice, filename, polyline_input):
    print("Graphing...")
    lines = decode_polyline(polyline_input)
    lat = []
    lon = []
    for line in lines:
        lon.append(line[0])
        lat.append(line[1])
    fig, ax = plt.subplots()
    ax.plot(lon, lat, color=color_choice, linewidth=5)
    ax.set_axis_off()
    plt.gca().set_aspect('equal', adjustable='box')
    plt.subplots_adjust(left=0,
                        bottom=0,
                        right=1,
                        top=1,
                        wspace=None,
                        hspace=None)
    f_name = './Render/' + str(filename) + '_Map.png'
    #plt.show()
    print("Saving...")
    fig.savefig(f_name, bbox_inches='tight', transparent='True')
    photos.create_image_asset(f_name)  #ios
コード例 #15
0
def save_photos_url(url, directory):
  os.makedirs('tmp', mode=0o777, exist_ok=True)
  some_album = check_for_album_or_make(directory)
  filename = url.split('/')[-1]
  path = 'tmp/' + filename
  urllib.request.urlretrieve(url, path)
  saved_asset = photos.create_image_asset(path)
  saved_asset.location = {
    'latitude': 45.0,
    'longitude': -135.0,
    'altitude': 10.0
  }
  some_album.add_assets([saved_asset])
  return
コード例 #16
0
def main():
    opt = dialogs.list_dialog('Select Mode', location_options)
    if opt is None:
        return
    elif opt['coords'] == (0, 0):
        # Use current location
        loc = get_location()
    else:
        loc = opt['coords']
    if loc:
        w, h = 540, 540  # Size of the image (points)
        map_w, map_h = 500, 500  # Size of the map (meters)
        lat, lng = loc
        img = location.render_map_snapshot(lat,
                                           lng,
                                           width=map_w,
                                           height=map_h,
                                           img_width=w,
                                           img_height=h,
                                           map_type='satellite')
        if not img:
            print('Failed not render map')
            return
        jpeg_data = img.to_jpeg()
        with open('.temp.jpg', 'wb') as f:
            f.write(jpeg_data)
        img.show()
        s = dialogs.alert(
            'Save to Photos?',
            'Do you want to save the image to your photo library?',
            'Save to Photos')
        if s == 1:
            photos.create_image_asset('.temp.jpg')
    else:
        print(
            'Cannot determine location. Try again later, or allow location access for Pythonista in the Settings app.'
        )
コード例 #17
0
def export_images():
    all_images = glob(os.path.join(
        'images',
        '*.png',
    ))
    
    album = photos.create_album('AWS Icon Export')
    album_assets = []
    for image in all_images:
        print('Processing Image: {}'.format(os.path.basename(image)))
        img_asset = photos.create_image_asset(image)
        album_assets.append(img_asset)
    
    print('Exporitng...')
    album.add_assets(album_assets)
コード例 #18
0
def add_asset(path, title=ALBUM_TITLE):
    """Add image to photo album 'Image Frame'."""
    try:
        coll = get_album(title)
        if not coll.can_add_assets:
            raise OSError
    except OSError:
        msg = "Sorry, album '%s' does not allow adding images." % title
        log.error(msg)
        abort(401, msg)
    else:
        asset = photos.create_image_asset(path)
        coll.add_assets([asset])
        log.debug("Added asset %s.", asset.local_id)
        return asset
コード例 #19
0
def save_image_to_album(img):
	img.save(".tmp.png", "PNG")
	album = get_album()
	asset = photos.create_image_asset(".tmp.png")
	album.add_assets([asset])	
コード例 #20
0
def again(sender):
    sound.play_effect('ui:click3')
    html = clipboard.get()  #Replace for debugging
    f = urllib.request.urlopen(html)  #Get the html of the instagram post
    htmlSource = f.read()  #Read it
    soup = BeautifulSoup(htmlSource, 'html.parser')  #Parse it
    v['textview'].text = (soup.title.text)  #Print the text of the post
    metaag = soup.find_all('script')  #Search for the script part of the html
    script2 = str(metaag)  #Convert it into a string
    substring = "display_url"
    counts = script2.count(
        substring)  #Count the number of times display-url appears
    metaTag = soup.find_all(
        'meta', {'property': 'og:video'})  #Find if there's a video in the post
    if metaTag:  #If video
        v['textview'].text = ('Downloading vidéo...')  #Update print
        #metaTag = soup.find_all('meta', {'property': 'og:video'})
        imgURL = metaTag[0]['content']  #Take the first one in the post
        urllib.request.urlretrieve(imgURL, 'fileName.mp4')
        PHPhotoLibrary = ObjCClass('PHPhotoLibrary')
        PHAssetChangeRequest = ObjCClass('PHAssetChangeRequest')

        def add_video():
            lib = PHPhotoLibrary.sharedPhotoLibrary()
            url = nsurl('fileName.mp4')  #Name of local video file

            def change_block():
                req = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL_(
                    url)

            def perform_changes():
                lib.performChangesAndWait_error_(change_block, None)

            t = threading.Thread(target=perform_changes)
            t.start()
            t.join()

        if __name__ == '__main__':
            add_video()
        v['textview'].text = ('Vidéo téléchargée dans votre galerie')
        os.remove('fileName.mp4')  #Clear files
    else:
        if counts == 1:  #if only one img
            metaTag = soup.find_all('meta', {'property': 'og:image'})
            imgURL = metaTag[0]['content']
            urllib.request.urlretrieve(imgURL, 'fileName.jpg')
            v['textview'].text = ('Image téléchargée dans votre galerie')
            photos.create_image_asset('fileName.jpg')
            os.remove('fileName.jpg')
        elif counts > 1:  #If multiples img
            txt = soup.select('script[type="text/javascript"]')[3]
            texte = txt.get_text()
            fille = open("tet.txt", 'w')
            fille.write(texte)
            fille.close()
            g = open('tet.txt', 'r')
            data = ''.join(g.readlines())
            le1 = 0
            le2 = 0
            hturl = open('url.html', 'w')
            still_looking = True
            while still_looking:
                still_looking = False
                dat = data.find('play_url', le1)
                det = data.find('play_resources', le2)
                if dat >= le1:
                    le1 = dat + 1
                    still_looking = True
                if det >= le2:
                    hturl.write(data[dat:det])
                    le2 = det + 1
                    still_looking = True
            hturl.close()
            hturl2 = open('url.html', 'r')
            dete = ''.join(hturl2.readlines())
            le11 = 0
            le22 = 0
            urls = []
            still_looking2 = True
            while still_looking2:
                still_looking2 = False
                dat2 = dete.find('https://instagram', le11)
                det2 = dete.find('","dis', le22)
                if dat2 >= le11:
                    urls.append(dat2)
                    le11 = dat2 + 1
                    still_looking2 = True
                if det2 >= le22:
                    urls.append(dete[dat2:det2])
                    le22 = det2 + 1
                    still_looking2 = True
            hturl2.close()
            imgs = len(urls)
            nbind = imgs
            nbindr = 3
            images = 1
            while nbindr < imgs:
                #print(urls)
                urllib.request.urlretrieve(urls[nbindr], 'photo.jpg')
                photos.create_image_asset('photo.jpg')
                v['textview'].text = ('Image ' + str(images) +
                                      ' téléchargée dans votre galerie')
                nbindr = nbindr + 2
                images += 1
            v['textview'].text = ("C'est bon")
            os.remove('photo.jpg')  #Remove all traces
            os.remove('tet.txt')
            os.remove('url.html')
    sound.play_effect('game:Ding_3')  #Sound for done
コード例 #21
0
import photos, PIL, os

pic_to_resize = photos.pick_asset()
img = pic_to_resize.get_image()
all_folders = photos.get_albums()
for album in all_folders:
    if album.title == 'medium-sized':
        meds = album
new_size = (int(pic_to_resize.pixel_width / 3),
            int(pic_to_resize.pixel_height / 3))
img_med = img.resize(new_size, PIL.Image.ANTIALIAS)
img_med.save('img_med.jpg')
new_med = photos.create_image_asset('img_med.jpg')
meds.add_assets([new_med])
try:
    os.remove('img_med.jpg')
except OSError:
    pass
コード例 #22
0
ファイル: ImageASCIIUI.py プロジェクト: cclauss/ImageToAscii
def save(sender):
    global text
    global imsize
    im = RenderASCII(text)
    im.save('Place.jpg')
    a = photos.create_image_asset('Place.jpg')
コード例 #23
0
def main():
    console.clear()
    userExit = 0
    args = None
    imageAssets = []
    pilImages = []

    while userExit <= 1:
        # get images
        if len(imageAssets) < 2:
            pilImages = []
            imageAssets = photos.pick_asset(title='Select images for collage',
                                            assets=photos.get_assets(),
                                            multi=True)
        if imageAssets is None:
            return

        # only keep photos
        imageAssets = [img for img in imageAssets if img.media_type == 'image']

        if len(imageAssets) < 2:
            userExit = dialogs.alert(title="Photo Collage",
                                     message="Select 3 or more images.",
                                     button1='OK',
                                     button3="Quit",
                                     hide_cancel_button=True)

        while userExit <= 2 and len(imageAssets) >= 2:
            # get user options
            args, userExit = getArgs(args)

            # get PIL image objects for all the photos
            if userExit <= 1 or len(pilImages) != len(imageAssets):
                print('Loading photos...')
                pilImages = []
                for f in imageAssets:
                    img = f.get_image()
                    if args['initheight'] >= 50 and img.height > args[
                            'initheight']:
                        if args['noantialias']:
                            pilImages.append(
                                img.resize((int(img.width / img.height *
                                                args['initheight']),
                                            args['initheight'])))
                        else:
                            pilImages.append(
                                img.resize((int(
                                    img.width / img.height *
                                    args['initheight']), args['initheight']),
                                           Image.ANTIALIAS))
                    else:
                        pilImages.append(img)
                imageList = [(i, imageAssets[i], pilImages[i])
                             for i in range(len(pilImages))]

            # shuffle images if needed
            if args['shuffle']:
                random.shuffle(imageList)
            else:
                imageList.sort(key=lambda img: img[0])

            print('Making collage...')

            collage = makeCollage([i[2] for i in imageList],
                                  spacing=args['imagegap'],
                                  antialias=not args['noantialias'],
                                  aspectratiofactor=args['aspectratiofactor'])

            if args['width'] >= 50 and collage.width > args['width']:
                collage = collage.resize(
                    (args['width'],
                     int(collage.height / collage.width * args['width'])),
                    Image.ANTIALIAS)
                pass
            elif args['height'] >= 50 and collage.height > args['height']:
                collage = collage.resize(
                    (int(collage.width / collage.height * args['height']),
                     args['height']), Image.ANTIALIAS)
                pass

            path = 'tmp.png'
            collage.save(path, format='PNG')
            console.quicklook(path)

            # ask to save if user didn't already save from the quicklook
            last_asset = photos.get_assets()[-1]
            if ((datetime.datetime.now() -
                 last_asset.creation_date).total_seconds() > 60
                    or last_asset.pixel_width != collage.width
                    or last_asset.pixel_height != collage.height
                ) and dialogs.alert('Save collage?',
                                    button1='Yes',
                                    button2='No',
                                    hide_cancel_button=True) == 1:
                photos.create_image_asset(path)
                print('Collage saved to camera roll...')
            os.remove(path)

            userExit = dialogs.alert(title="Finished!",
                                     button1='New w/ new pics',
                                     button2='New w/ same pics',
                                     button3='Quit',
                                     hide_cancel_button=True)
            if userExit == 1:
                imageAssets = []

            print('Finished!')