Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if not PYEXIV_AVAILABLE:
return []
def calc(k): return [(float(n)/float(d)) for n,d in [k.split("/")]][0]
def degtodec(a): return a[0]+a[1]/60+a[2]/3600
def format_coordinates(string):
return degtodec([(calc(i)) for i in (string.split(' ')) if ("/" in i)])
def format_coordinates_alter(tuple):
return degtodec(((float(tuple[0].numerator)/float(tuple[0].denominator)), (float(tuple[1].numerator)/float(tuple[1].denominator)), (float(tuple[2].numerator)/float(tuple[2].denominator))))
try:
#Check if pyexiv2 v0.3 is installed
if 'ImageMetadata' in dir(pyexiv2):
exif_data = pyexiv2.ImageMetadata(temp_file)
exif_data.read()
keys = exif_data.exif_keys
if "Exif.GPSInfo.GPSLatitude" in keys :
coordinates = {}
coordinates['from'] = 'exif'
coordinates['context'] = ('https://twitter.com/%s/status/%s' % (tweet.user.screen_name, tweet.id) , 'Location retrieved from image exif metadata .\n Tweet was %s \n ' % (tweet.text))
coordinates['time'] = datetime.fromtimestamp(mktime(time.strptime(exif_data['Exif.Image.DateTime'].raw_value, "%Y:%m:%d %H:%M:%S")))
coordinates['latitude'] = format_coordinates(exif_data['Exif.GPSInfo.GPSLatitude'].raw_value)
coordinates['realname'] = tweet.user.name
lat_ref = exif_data['Exif.GPSInfo.GPSLatitudeRef'].raw_value
if lat_ref == 'S':
coordinates['latitude'] = -coordinates['latitude']
coordinates['longitude'] = format_coordinates(exif_data['Exif.GPSInfo.GPSLongitude'].raw_value)
long_ref = exif_data['Exif.GPSInfo.GPSLongitudeRef'].raw_value
if long_ref == 'W':
coordinates['longitude'] = -coordinates['longitude']
def load_images(self):
files = []
self.pictures = []
path = self.image_dir
for file in os.listdir(path):
if fnmatch.fnmatch(file, '*.jpg') or fnmatch.fnmatch(file, '*.JPG'):
files.append(file)
files.sort()
last_trigger = 0.0
interval = 0
for f in files:
name = path + "/" + f
print name
exif = pyexiv2.ImageMetadata(name)
exif.read()
# print exif.exif_keys
strdate, strtime = str(exif['Exif.Image.DateTime'].value).split()
year, month, day = strdate.split('-')
formated = year + "/" + month + "/" + day + " " + strtime + " UTC"
result, unixtimestr = commands.getstatusoutput('date -d "' + formated + '" "+%s"' )
unixtime = float(unixtimestr)
# print f + ": " + strdate + ", " + strtime + ", " + unixtimestr
if last_trigger > 0.0:
interval = unixtime - last_trigger
self.pictures.append( (unixtime, interval, f) )
last_trigger = unixtime
def open_image(self,path=''):
if not path:
default=''
if self.path:
default=os.path.split(self.path)[0]
path=file_dialog(default=default)
if not path:
return
self.path=os.path.abspath(path)
# Load the image, read the metadata
try:
metadata = pyexiv2.ImageMetadata(self.path)
metadata.read()
except:
self.imgwidget.clear()
self.model.clear()
self.set_title("Metadata Viewer")
return
self.set_title("Metadata Viewer - %s"%(path,))
#extract the thumbnail data
previews = metadata.previews
if previews:
preview = previews[-1]
# Get the largest preview available
# Create a pixbuf loader to read the thumbnail data
pbloader = gtk.gdk.PixbufLoader()
pbloader.write(preview.data)
def add_exif_using_timestamp(filename, points, offset_time=0, timestamp=None, orientation=1, image_description=None):
'''
Find lat, lon and bearing of filename and write to EXIF.
'''
metadata = pyexiv2.ImageMetadata(filename)
metadata.read()
if timestamp:
metadata['Exif.Photo.DateTimeOriginal'] = timestamp
t = metadata['Exif.Photo.DateTimeOriginal'].value
# subtract offset in s beween gpx time and exif time
t = t - datetime.timedelta(seconds=offset_time)
try:
lat, lon, bearing, elevation = interpolate_lat_lon(points, t)
lat_deg = to_deg(lat, ["S", "N"])
lon_deg = to_deg(lon, ["W", "E"])
# convert decimal coordinates into degrees, minutes and seconds as fractions for EXIF
else:
# prevent writing or reading from non MIME images
return
# make sure media is on the computer?
image_path = Utils.media_path_full(self.dbstate.db, active_media.get_path() )
if not os.path.exists(image_path):
return
# make sure the file permissions allow reading?
readable = os.access(image_path, os.R_OK)
if not readable:
return
# define plugin media
self.plugin_image = pyexiv2.ImageMetadata(image_path)
if LesserVersion:
try:
self.plugin_image.readMetadata()
except IOError:
return
else:
# read media metadata
try:
self.plugin_image.read()
except IOError:
return
# set up image metadata keys for use in this gramplet
def SetGpsLocation(file_name, gps_datetime, lat, lng, alt):
"""
Adding GPS tag
"""
lat_deg = to_degree(lat, ["S", "N"])
lng_deg = to_degree(lng, ["W", "E"])
exiv_lat = (pyexiv2.Rational(lat_deg[0] * 60 + lat_deg[1], 60), pyexiv2.Rational(
lat_deg[2] * 100, 6000), pyexiv2.Rational(0, 1))
exiv_lng = (pyexiv2.Rational(lng_deg[0] * 60 + lng_deg[1], 60), pyexiv2.Rational(
lng_deg[2] * 100, 6000), pyexiv2.Rational(0, 1))
exiv_image = pyexiv2.ImageMetadata(file_name)
exiv_image.read()
date_tag = exiv_image['Exif.Image.DateTime']
date_max = max(date_tag.value, gps_datetime)
date_min = min(date_tag.value, gps_datetime)
time_diff = date_max - date_min
if (time_diff > timedelta(seconds=5)):
print(
"WARNING, camera trigger and photo time different by {}".format(time_diff))
print(" Photo tag time: {}".format(date_tag.value))
print(" Camera trigger time: {}".format(gps_datetime))
exiv_image["Exif.GPSInfo.GPSLatitude"] = exiv_lat
exiv_image["Exif.GPSInfo.GPSLatitudeRef"] = lat_deg[3]
exiv_image["Exif.GPSInfo.GPSLongitude"] = exiv_lng
def get_exif_data(image_path):
exiv_image = pyexiv2.ImageMetadata(image_path)
exiv_image.read()
print exiv_image.exif_keys
exif_keys = exiv_image.exif_keys
if ("Exif.GPSInfo.GPSLatitude" in exif_keys and "Exif.GPSInfo.GPSLongitude" in exif_keys and "Exif.GPSInfo.GPSLongitudeRef" in exif_keys and "Exif.GPSInfo.GPSLatitudeRef" in exif_keys):
# convert rational values into decimal
tag_lat = exiv_image["Exif.GPSInfo.GPSLatitude"]
tag_lng = exiv_image["Exif.GPSInfo.GPSLongitude"]
lat = float(tag_lat.value[0].numerator/tag_lat.value[0].denominator) + float(float(tag_lat.value[1].numerator/tag_lat.value[1].denominator)/ 60) + float(float(tag_lat.value[2].numerator/tag_lat.value[2].denominator)/ 3600)
lng = float(tag_lng.value[0].numerator/tag_lng.value[0].denominator) + float(float(tag_lng.value[1].numerator/tag_lng.value[1].denominator)/ 60) + float(float(tag_lng.value[2].numerator/tag_lng.value[2].denominator)/ 3600)
if exiv_image["Exif.GPSInfo.GPSLongitudeRef"].raw_value == "W":
lng = lng * -1 # (W is -, E is +)
if exiv_image["Exif.GPSInfo.GPSLatitudeRef"].raw_value == "S":
lat = lat * -1
"""
This will:
* create the plugin image instance if needed,
* setup the tooltips for the data fields,
* setup the tooltips for the buttons,
"""
if OLD_API: # prior to pyexiv2-0.2.0
metadata = pyexiv2.Image(full_path)
try:
metadata.readMetadata()
except (IOError, OSError):
self.set_has_data(False)
metadata = False
else: # pyexiv2-0.2.0 and above
metadata = pyexiv2.ImageMetadata(full_path)
try:
metadata.read()
except (IOError, OSError):
self.set_has_data(False)
metadata = False
return metadata
font_size = image_font_size
# centre text and compensate for graphics text being wider
x = int(( image_width / 2) - (len( text_to_print ) * font_size / 4) )
if image_text_bottom:
y = ( image_height - 50 ) # show text at bottom of image
else:
y = 10 # show text at top of image
TEXT = text_to_print
font_path = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf'
font = ImageFont.truetype( font_path, font_size, encoding='unic' )
text = TEXT.decode( 'utf-8' )
# Read exif data since ImageDraw does not save this metadata
if not (sys.version_info > (3, 0)):
metadata = pyexiv2.ImageMetadata(image_filename)
metadata.read()
img = Image.open( image_filename )
draw = ImageDraw.Draw( img )
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text( ( x, y ), text, FOREGROUND, font=font )
img.save( image_filename )
if not (sys.version_info > (3, 0)):
metadata.write() # Write previously saved exif data to image file
msgStr = " Image Saved - " + text_to_print
show_message("image_write ", msgStr)
return
except IOError:
self.set_has_data(False)
return
metadata.readMetadata()
for key in metadata.exifKeys():
label = metadata.tagDetails(key)[0]
if key in ("Exif.Image.DateTime",
"Exif.Photo.DateTimeOriginal",
"Exif.Photo.DateTimeDigitized"):
human_value = format_datetime(metadata[key])
else:
human_value = metadata.interpretedExifValue(key)
self.model.add((label, human_value))
else: # v0.2.0 and above
metadata = pyexiv2.ImageMetadata(full_path)
try:
metadata.read()
except IOError:
self.set_has_data(False)
return
for key in metadata.exif_keys:
tag = metadata[key]
if key in ("Exif.Image.DateTime",
"Exif.Photo.DateTimeOriginal",
"Exif.Photo.DateTimeDigitized"):
human_value = format_datetime(tag.value)
else:
human_value = tag.human_value
self.model.add((tag.label, human_value))
self.set_has_data(self.model.count > 0)