laravel-image 0.2.0

Image handling and manipulation for Laravel Rust, in pure Rust: a port of intervention/image-laravel and Intervention Image.
Documentation
//! Exif data, grouped in the sections of PHP's `exif_read_data()`.

use serde_json::{Map, Value};

/// The Exif data of a decoded image, grouped like PHP's `exif_read_data($file, null, true)`:
/// `IFD0`, `THUMBNAIL`, `EXIF`, `GPS` and `INTEROP`. Integer tags are numbers, text tags are
/// strings, other tags their readable value.
///
/// ```ignore
/// let orientation = image.exif().get("IFD0.Orientation"); // Some(6)
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Exif(Map<String, Value>);

impl Exif {
    /// `$image->exif($query)`: a section (`EXIF`) or a tag in dot notation (`IFD0.Orientation`).
    pub fn get(&self, query: &str) -> Option<&Value> {
        let mut parts = query.split('.');
        let mut value = self.0.get(parts.next()?)?;
        for part in parts {
            value = value.get(part)?;
        }
        Some(value)
    }

    /// Every section and tag.
    pub fn all(&self) -> &Map<String, Value> {
        &self.0
    }

    /// No Exif data was found.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// The `IFD0.Orientation` tag as a number.
    pub fn orientation(&self) -> Option<u64> {
        self.get("IFD0.Orientation").and_then(Value::as_u64)
    }

    pub(crate) fn set_orientation(&mut self, orientation: u64) {
        for section in self.0.values_mut() {
            if let Some(tags) = section.as_object_mut()
                && tags.contains_key("Orientation")
            {
                tags.insert("Orientation".to_owned(), Value::from(orientation));
            }
        }
    }

    pub(crate) fn read(bytes: &[u8]) -> Exif {
        let Ok(data) = exif::Reader::new().read_from_container(&mut std::io::Cursor::new(bytes)) else {
            return Exif::default();
        };
        let mut sections = Map::new();
        for field in data.fields() {
            let section = match field.tag.context() {
                exif::Context::Tiff if field.ifd_num == exif::In::PRIMARY => "IFD0",
                exif::Context::Tiff => "THUMBNAIL",
                exif::Context::Exif => "EXIF",
                exif::Context::Gps => "GPS",
                exif::Context::Interop => "INTEROP",
                _ => continue,
            };
            let value = match &field.value {
                exif::Value::Ascii(values) => Value::from(
                    values
                        .first()
                        .map(|v| String::from_utf8_lossy(v).into_owned())
                        .unwrap_or_default(),
                ),
                exif::Value::Byte(values) if values.len() == 1 => Value::from(values[0]),
                exif::Value::Short(values) if values.len() == 1 => Value::from(values[0]),
                exif::Value::Long(values) if values.len() == 1 => Value::from(values[0]),
                exif::Value::SShort(values) if values.len() == 1 => Value::from(values[0]),
                exif::Value::SLong(values) if values.len() == 1 => Value::from(values[0]),
                exif::Value::Rational(values) if values.len() == 1 => {
                    Value::from(format!("{}/{}", values[0].num, values[0].denom))
                }
                _ => Value::from(field.display_value().to_string()),
            };
            sections
                .entry(section.to_owned())
                .or_insert_with(|| Value::Object(Map::new()))
                .as_object_mut()
                .map(|tags| tags.insert(field.tag.to_string(), value));
        }
        Exif(sections)
    }
}