def get_images(): response = [] image_names = os.listdir('static/images') for image_name in image_names: with open(f"static/images/{image_name}", "rb") as image_file: image = Image(image_file) for val in dir(image): print(val) response.append({ 'path': f'static/images/{image_name}', 'model': image.get('model', None) if image.has_exif else None, 'lens': image.get('lens_model', None) if image.has_exif else None, 'taken': image.get('datetime_original', None) if image.has_exif else None, 'focalLength': image.get('focal_length', None) if image.has_exif else None, 'exposureMode': image.get('exposure_mode', None) if image.has_exif else None, 'apertureValue': image.get('aperture_value', None) if image.has_exif else None, 'shutterSpeedValue': image.get('shutter_speed_value', None) if image.has_exif else None, 'sceneCaptureType': image.get('scene_capture_type', None) if image.has_exif else None, 'software': image.get('software', None) if image.has_exif else None, 'colorSpace': image.get('color_space', None) if image.has_exif else None, }) return app.response_class(mimetype='application/json', response=json.dumps(response))
def test_get_method(): """Test behavior when accessing tags using the ``get()`` method.""" with open(os.path.join(os.path.dirname(__file__), 'grand_canyon.jpg'), 'rb') as image_file: image = Image(image_file) assert image.get('fake_attribute') is None assert image.get('light_source', default=-1) == -1 # tag not in image assert image.get('make') == Baseline("""Apple""")
def get_date_taken(file_path: Path) -> datetime: try: with open(str(file_path), 'rb') as file: my_image = Image(file) if my_image.has_exif: date_time = my_image.get('datetime_original') if date_time is not None: return pendulum.from_format(date_time, "YYYY:MM:DD HH:mm:ss") except AssertionError: properties = propsys.SHGetPropertyStoreFromParsingName(str(file_path)) dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() if dt is None: dt = properties.GetValue(pscon.PKEY_Media_DateReleased).GetValue() if dt is None: dt = properties.GetValue(pscon.PKEY_Photo_DateTaken).GetValue() if dt is None: dt = properties.GetValue( pscon.PKEY_RecordedTV_OriginalBroadcastDate).GetValue() if dt is not None: return pendulum.instance(dt) return None
def get_image_take_date(f_name): # print('FileMetaData : get_image_take_date : f_name = ', f_name) t, exception = f_name.split('.', -1) if exception.lower() == 'png': # from tkinter import simpledialog # date_string = simpledialog.askstring("set date [format: yyyy:mm:dd hh:mm:ss]", f_name) # print('FileMetaData : get_image_take_date : user input - date_string = ', date_string) # if date_string: # return date_string # else: return None try: with open(f_name, 'rb') as image_file: my_image = Image(image_file) if my_image.has_exif: date_string = my_image.get('datetime') if date_string: if "?" in date_string: return None else: # print('FileMetaData : get_image_take_date : file read - date_string = ', date_string) return date_string else: return None else: return None except NameError: return None
def get_image_orientation(f_name): try: with open(f_name, 'rb') as image_file: my_image = Image(image_file) if my_image.has_exif: return my_image.get('orientation') except NameError: return None
def upload(): payload = {} file = request.files['file'] file.save("tmp_uploads/" + file.filename) fname = file.filename.split('.') if fname[-1].lower() != "jpg": flash("Incompatibe image format. Please use JPG", "warning") else: payload['name'] = file.filename if 'file' in request.files: with open("tmp_uploads/" + file.filename, 'rb') as imgfile: image_enc = base64.b64encode(imgfile.read()) imgfile.seek(0) myimage = Image(imgfile) if myimage.has_exif == False: flash("Image does not have exif metadata") else: payload['image'] = str(image_enc)[2:-1] payload['metadata'] = {} for attr in dir(myimage): try: value = myimage.get(attr) if value != None or value != null or ( type(value) not in [float, int, str]): payload['metadata'][attr] = myimage.get(attr) if type(payload['metadata'][attr]) == str: payload['metadata'][attr] = payload[ 'metadata'][attr].strip() if attr not in status.ATTRIBUTES_SET and ( attr[0] != "_" and attr not in [ 'user_comment', "MakerNote" ]) and str(type(value)) in [ "<class 'float'>", "<class 'int'>", "float", "int" ]: status.ATTRIBUTES_SET.append(attr) except: continue r = requests.post("http://localhost:5000/create_record", json=payload) return redirect(url_for('home'))
def photo_upload(): if request.method == 'GET': return photo_upload_page() category = request.values.get('category') or request.values.get( 'category_new') date = datetime.strptime(request.values.get('date'), '%Y-%m-%d') photos = request.files.getlist('photo') description = request.values.get('description') if not category or not date or not photos: errors = {'category': category, 'date': date, 'photo': photos} return photo_upload_page( errors=[k for k, v in errors.items() if not v]) for photo in photos: try: exif = ExifImage(photo.stream) if exif.has_exif: date_str = exif.get('datetime_original') or exif.get( 'datetime') if date_str: photo_date = datetime.strptime(date_str, '%Y:%m:%d %H:%M:%S') else: photo_date = date except: photo_date = date photo.stream.seek(0) extension = get_extension(photo.filename) filename = f'{random.key(16)}.{extension}' photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) thumbnail(os.path.join(app.config['UPLOAD_FOLDER'], filename)) db.session.add( Photo(creator_id=current_user.id, category=category, description=description, filename=filename, creation_date=photo_date)) # Commit per photo in case upload fails halfway db.session.commit() return redirect(url_for('show_albums'))
def get_image_exif_info(filename_with_path: str): """ Try to get exif info from file (datetime_original). :return: image_date_converted : string, or None """ with open(filename_with_path, 'rb') as image_file: try: my_image = Image(image_file) image_date = my_image.get('datetime_original', None) if image_date: # az exif információ átalakítása image_date = image_date.replace(chr(0), "") exif_info_date = image_date.replace(":", '_').replace(" ", '_') return exif_info_date else: return None except: # ha a fájl kiterjesztés képre utal, de mégsem # traceback.print_exc() return None
def get_metadata(filepath): metadata = {} # read the image data using exif with open(filepath, "rb") as image_file: image = Image(image_file) metadata = { 'Date Taken': image.get('datetime_digitized'), 'Device Used': image.get('model'), 'Location': get_location( get_decimal_from_dms(image.get('gps_latitude'), image.get('gps_latitude_ref')), get_decimal_from_dms(image.get('gps_longitude'), image.get('gps_longitude_ref')), ) } return metadata
# -*- coding: utf-8 -*- import os from exif import Image import datetime import time #import filecmp import hashlib with open( "/home/bakog/Dropbox/phyton/image_renamer_by_exif/sample_data/pictures_without_exif/DSCN0017.JPG", 'rb') as image_file: my_image = Image(image_file) image_date = my_image.get('datetime_original', None) image_date_converted = image_date.replace(":", '_').replace(" ", '_') print(len(image_date_converted)) print(image_date_converted.strip('\n\l')) print(image_date_converted.replace(chr(0), "")) for c in image_date_converted: print(ord(c))
path = input("Enter the file path: ") try: #Open image with open(path, 'rb') as imageFile: image = Image(imageFile) #Verify that image has associated EXIF metadata available to be read if image.has_exif: imageAttributes = dir(image) for attribute in imageAttributes: try: # For some reason user comment is a bunch of non-ascii character jiberish if(attribute != 'user_comment'): # Print metadata print(attribute +': ' + str(image.get(attribute))) except: # Some attributes are unreadable so throw exception print("Image contains unreadable attribute: " + str(attribute)) # Return error otherwise else : print('Error, file exists but there is no EXIF Metadata present') # Handle file not found except FileNotFoundError: print("Error: File not found, please make sure the file path specified is correct") # Handle all other unexpected exceptions except Exception as e: print("Error, an exception was encountered: " + str(e))
class TestReadExif(unittest.TestCase): """Test cases for reading EXIF attributes.""" def setUp(self): """Open sample image file in binary mode for use in test cases.""" grand_canyon = os.path.join(os.path.dirname(__file__), 'grand_canyon.jpg') with open(grand_canyon, 'rb') as image_file: self.image = Image(image_file) assert self.image.has_exif def test_get_method(self): """Test behavior when accessing tags using the ``get()`` method.""" self.assertIsNone(self.image.get('fake_attribute')) self.assertEqual(self.image.get('light_source', default=-1), -1) # tag not in image self.assertEqual(self.image.get('make'), Baseline("""Apple""")) def test_handle_bad_attribute(self): """Verify that accessing a nonexistent attribute raises an AttributeError.""" with self.assertRaisesRegex(AttributeError, "unknown image attribute fake_attribute"): self.image.fake_attribute def test_handle_unset_attribute(self): """Verify that accessing an attribute not present in an image raises an AttributeError.""" with self.assertRaisesRegex(AttributeError, "image does not have attribute light_source"): self.image.light_source def test_index_accessor(self): """Test accessing attributes using index syntax.""" self.assertEqual(self.image["datetime"], Baseline("""2018:03:12 10:12:07""")) def test_read_ascii(self): """Test reading ASCII tags and compare to known baseline values.""" self.assertEqual(self.image.datetime, Baseline("""2018:03:12 10:12:07""")) self.assertEqual(self.image.make, Baseline("""Apple""")) self.assertEqual(self.image.model, Baseline("""iPhone 7""")) self.assertEqual(self.image.gps_latitude_ref, Baseline("""N""")) self.assertEqual(self.image.gps_longitude_ref, Baseline("""W""")) def test_read_byte(self): """Test reading BYTE tags and compare to known baseline values.""" self.assertEqual(str(self.image.gps_altitude_ref), Baseline("""0""")) def test_read_exif_version(self): """Test reading EXIF version tag and compare to known baseline values.""" self.assertEqual(self.image.exif_version, Baseline("0221")) def test_read_long(self): """Test reading LONG tags and compare to known baseline values.""" self.assertEqual(str(self.image.jpeg_interchange_format), Baseline("""6410""")) self.assertEqual(str(self.image.jpeg_interchange_format_length), Baseline("""4507""")) def test_read_rational(self): """Test reading RATIONAL tags and compare to known baseline values.""" self.assertEqual(str(self.image.gps_altitude)[:13], Baseline("""2189.98969072""")) self.assertEqual(str(self.image.gps_latitude), Baseline("""(36.0, 3.0, 11.08)""")) self.assertEqual(str(self.image.gps_longitude), Baseline("""(112.0, 5.0, 4.18)""")) self.assertEqual(str(self.image.x_resolution), Baseline("""72.0""")) self.assertEqual(str(self.image.y_resolution), Baseline("""72.0""")) def test_read_short(self): """Test reading a SHORT tag and compare to a known baseline value.""" self.assertEqual(str(self.image.metering_mode), Baseline("""5""")) def test_read_srational(self): """Test reading a SRATIONAL tag and compare to a known baseline value.""" self.assertEqual(str(self.image.brightness_value)[:13], Baseline("""11.3644957983"""))
def get_exif(image, row): with open(image['file'], 'rb') as image_file: my_image = ExifImage(image_file) if my_image.has_exif: for tag in EXIF_TAGS: row[tag] = my_image.get(tag)
from exif import Image with open("BIL.jpg", "rb") as bil: photo = Image(bil) if photo.has_exif: print(photo.get("datetime")) print(photo.get("gps_altitude")) print(photo.get("gps_longitude")) print(photo.get("gps_latitude")) print(photo.get("make")) print(photo.get("model")) print(photo.get("software"))
from exif import Image from pprint import pprint as pp fn=r'in\Hibla_gerzmava_is_a_war_supporter.JPG' with open(fn, 'rb') as image_file: my_image = Image(image_file) print(my_image.has_exif) pp(dir(my_image)) print(my_image.get('width'))