Skip to content

Instantly share code, notes, and snippets.

@jessearmand
Last active March 25, 2023 08:11
Show Gist options
  • Save jessearmand/feadf847b59a11b4916a02c14fa12f2c to your computer and use it in GitHub Desktop.
Save jessearmand/feadf847b59a11b4916a02c14fa12f2c to your computer and use it in GitHub Desktop.
Parse latitude longitude information from Exif tag for files in a directory (initial boilerplate from you.com, improved with kamadak-exif sample code)
use std::env;
use std::fs;
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
use exif::{In, Reader, Tag};
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
println!("Usage: {} <photo_directory>", args[0]);
return;
}
let photo_dir = &args[1];
println!("Photo directory {}", photo_dir);
match fs::read_dir(PathBuf::from(photo_dir)) {
Ok(paths) => {
for path in paths {
let file_path = path.unwrap().path();
println!("path {}", file_path.display());
let file_name = file_path.file_name().unwrap().to_str().unwrap().to_lowercase();
if file_name.ends_with(".jpg") || file_name.ends_with(".jpeg") || file_name.ends_with(".mp4") || file_name.ends_with("mov") {
let file = File::open(&file_path).unwrap();
let exif = Reader::new().read_from_container(
&mut BufReader::new(file)).unwrap();
// To obtain a string representation, `Value::display_as`
// or `Field::display_value` can be used. To display a value with its
// unit, call `with_unit` on the return value of `Field::display_value`.
let tag_list = [Tag::ExifVersion,
Tag::PixelXDimension,
Tag::XResolution,
Tag::ImageDescription,
Tag::DateTime];
for tag in tag_list {
if let Some(field) = exif.get_field(tag, In::PRIMARY) {
println!("{}: {}",
field.tag, field.display_value().with_unit(&exif));
}
}
if let Some(latitude) = exif.get_field(Tag::GPSLatitude, In::PRIMARY) {
println!("Latitude: {}", latitude.display_value().with_unit(&exif));
}
if let Some(longitude) = exif.get_field(Tag::GPSLongitude, In::PRIMARY) {
println!("Longitude: {}", longitude.display_value().with_unit(&exif));
}
println!("File name: {}", file_name);
}
}
}
Err(e) => {
println!("Error: {:?}", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment