### Install goexif/exif Package Source: https://github.com/rwcarlsen/goexif/blob/go1/README.md Command to install the exif package from the goexif library. This package depends on the tiff package. ```bash go get github.com/rwcarlsen/goexif/exif ``` -------------------------------- ### Install goexif/tiff Package Source: https://github.com/rwcarlsen/goexif/blob/go1/README.md Command to install only the tiff package from the goexif library. This is a dependency for the exif package. ```bash go get github.com/rwcarlsen/goexif/tiff ``` -------------------------------- ### Decode EXIF Data from Image File Source: https://github.com/rwcarlsen/goexif/blob/go1/README.md Go code example demonstrating how to open an image file, decode its EXIF metadata, and extract specific tags like camera model, focal length, date taken, and GPS coordinates. It also shows how to register parsers for camera makenote data. ```go package main import ( "fmt" "log" "os" "github.com/rwcarlsen/goexif/exif" "github.com/rwcarlsen/goexif/mknote" ) func ExampleDecode() { fname := "sample1.jpg" f, err := os.Open(fname) if err != nil { log.Fatal(err) } // Optionally register camera makenote data parsing - currently Nikon and // Canon are supported. exif.RegisterParsers(mknote.All...) x, err := exif.Decode(f) if err != nil { log.Fatal(err) } camModel, _ := x.Get(exif.Model) // normally, don't ignore errors! fmt.Println(camModel.StringVal()) focal, _ := x.Get(exif.FocalLength) numer, denom, _ := focal.Rat2(0) // retrieve first (only) rat. value fmt.Printf("%v/%v", numer, denom) // Two convenience functions exist for date/time taken and GPS coords: tm, _ := x.DateTime() fmt.Println("Taken: ", tm) lat, long, _ := x.LatLong() fmt.Println("lat, long: ", lat, ", ", long) } ``` -------------------------------- ### Retrieve Specific EXIF Tags Source: https://context7.com/rwcarlsen/goexif/llms.txt Shows how to extract individual EXIF tags such as Make, Model, Focal Length, and ISO. It demonstrates handling tag retrieval errors and converting values into strings, integers, or rational numbers. ```go package main import ( "fmt" "log" "os" "github.com/rwcarlsen/goexif/exif" ) func main() { f, _ := os.Open("photo.jpg") defer f.Close() x, _ := exif.Decode(f) makeTag, err := x.Get(exif.Make) if err != nil { if exif.IsTagNotPresentError(err) { fmt.Println("Make tag not present") } } else { makeVal, _ := makeTag.StringVal() fmt.Printf("Camera Make: %s\n", makeVal) } focalTag, _ := x.Get(exif.FocalLength) num, denom, _ := focalTag.Rat2(0) fmt.Printf("Focal Length: %d/%d mm\n", num, denom) isoTag, _ := x.Get(exif.ISOSpeedRatings) iso, _ := isoTag.Int(0) fmt.Printf("ISO: %d\n", iso) } ``` -------------------------------- ### Exif.Walk Source: https://context7.com/rwcarlsen/goexif/llms.txt Iterates over all EXIF fields using a Walker interface. ```APIDOC ## GET Exif.Walk ### Description Iterates over all EXIF fields in the image by calling a Walker interface for each tag. Useful for custom metadata processing. ### Method Internal Method (Go Library) ### Endpoint x.Walk(walker) ### Parameters - **walker** (interface) - Required - An implementation of the Walk method that accepts (name exif.FieldName, tag *tiff.Tag) ``` -------------------------------- ### Registering Makernote Parsers in goexif Source: https://context7.com/rwcarlsen/goexif/llms.txt Demonstrates how to register manufacturer-specific makernote parsers using exif.RegisterParsers. This must be performed before calling exif.Decode to ensure camera-specific metadata like Canon or Nikon fields are correctly parsed. ```go package main import ( "fmt" "os" "github.com/rwcarlsen/goexif/exif" "github.com/rwcarlsen/goexif/mknote" ) func main() { exif.RegisterParsers(mknote.All...) f, _ := os.Open("canon_photo.jpg") defer f.Close() x, _ := exif.Decode(f) if lensModel, err := x.Get("Canon.LensModel"); err == nil { val, _ := lensModel.StringVal() fmt.Printf("Lens: %s\n", val) } if focusMode, err := x.Get("Canon.FocusMode"); err == nil { val, _ := focusMode.Int(0) fmt.Printf("Focus Mode: %d\n", val) } } ``` -------------------------------- ### Read EXIF Camera and Exposure Data using GoExif Source: https://context7.com/rwcarlsen/goexif/llms.txt This Go code snippet demonstrates how to use the goexif library to extract camera information (manufacturer, model, software, artist, copyright) and exposure settings (shutter speed, aperture, ISO, focal length, exposure program, metering mode, flash) from a JPEG image. It utilizes predefined constants for EXIF field names and handles potential errors during data retrieval. ```go package main import ( "fmt" "os" "github.com/rwcarlsen/goexif/exif" ) func main() { f, _ := os.Open("photo.jpg") defer f.Close() x, _ := exif.Decode(f) // Camera information fields fields := []exif.FieldName{ exif.Make, exif.Model, exif.Software, exif.Artist, exif.Copyright, } fmt.Println("Camera Info:") for _, field := range fields { if tag, err := x.Get(field); err == nil { val, _ := tag.StringVal() fmt.Printf(" %s: %s\n", field, val) } } // Exposure settings exposureFields := []exif.FieldName{ exif.ExposureTime, exif.FNumber, exif.ISOSpeedRatings, exif.FocalLength, exif.ExposureProgram, exif.MeteringMode, exif.Flash, } fmt.Println("\nExposure Settings:") for _, field := range exposureFields { if tag, err := x.Get(field); err == nil { fmt.Printf(" %s: %s\n", field, tag.String()) } } // GPS fields gpsFields := []exif.FieldName{ exif.GPSLatitude, exif.GPSLatitudeRef, exif.GPSLongitude, exif.GPSLongitudeRef, exif.GPSAltitude, exif.GPSDateStamp, } fmt.Println("\nGPS Data:") for _, field := range gpsFields { if tag, err := x.Get(field); err == nil { fmt.Printf(" %s: %s\n", field, tag.String()) } } } ``` -------------------------------- ### Handle EXIF Decoding Errors with GoExif Source: https://context7.com/rwcarlsen/goexif/llms.txt This Go code snippet illustrates how to handle errors during EXIF data decoding using the goexif library. It demonstrates checking for critical errors, and specific types of non-critical errors like EXIF, GPS, Interoperability, and Short Read Tag Value errors. The code also shows how to gracefully continue processing with partial data and check for the presence of specific tags. ```go package main import ( "fmt" "log" "os" "github.com/rwcarlsen/goexif/exif" ) func main() { f, _ := os.Open("possibly_corrupt.jpg") defer f.Close() x, err := exif.Decode(f) if err != nil { // Check if error is critical (no usable data) if exif.IsCriticalError(err) { log.Fatalf("Critical error, cannot proceed: %v", err) } // Non-critical errors - some data may still be available if exif.IsExifError(err) { fmt.Println("Warning: Error in EXIF sub-IFD, some fields unavailable") } if exif.IsGPSError(err) { fmt.Println("Warning: Error in GPS sub-IFD, GPS data unavailable") } if exif.IsInteroperabilityError(err) { fmt.Println("Warning: Error in Interoperability sub-IFD") } if exif.IsShortReadTagValueError(err) { fmt.Println("Warning: Truncated tag value detected") } fmt.Printf("Continuing with partial data: %v\n", err) } // Try to access available data if tag, err := x.Get(exif.Model); err == nil { val, _ := tag.StringVal() fmt.Printf("Model: %s\n", val) } else if exif.IsTagNotPresentError(err) { fmt.Println("Model tag not present in this image") } // Output: // Warning: Error in GPS sub-IFD, GPS data unavailable // Continuing with partial data: loading GPS sub-IFD: ... // Model: Canon EOS 5D } ``` -------------------------------- ### Decoding TIFF Structures with tiff.Decode Source: https://context7.com/rwcarlsen/goexif/llms.txt Shows how to use the low-level tiff.Decode function to parse raw TIFF files. It allows for iterating through Image File Directories (IFDs) and inspecting individual tags. ```go package main import ( "fmt" "os" "github.com/rwcarlsen/goexif/tiff" ) func main() { f, _ := os.Open("image.tif") defer f.Close() t, err := tiff.Decode(f) if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Byte order: %v\n", t.Order) fmt.Printf("Number of IFDs: %d\n", len(t.Dirs)) for i, dir := range t.Dirs { fmt.Printf("\nIFD %d (%d tags):\n", i, len(dir.Tags)) for _, tag := range dir.Tags { fmt.Printf(" Tag 0x%04X: Type=%v Count=%d\n", tag.Id, tag.Type, tag.Count) } } } ``` -------------------------------- ### exif.RegisterParsers Source: https://context7.com/rwcarlsen/goexif/llms.txt Registers manufacturer-specific makernote parsers to enable extended EXIF metadata extraction for specific camera models. ```APIDOC ## exif.RegisterParsers ### Description Registers additional parsers for processing camera-specific makernote data. This must be invoked before calling exif.Decode() to ensure manufacturer-specific tags are correctly parsed. ### Method Function Call ### Parameters #### Arguments - **parsers** (...Parser) - Required - A variadic list of makernote parsers (e.g., mknote.Canon, mknote.NikonV3). ### Request Example ```go exif.RegisterParsers(mknote.All...) ``` ### Response - **void** - Returns nothing; modifies global state for the decoder. ``` -------------------------------- ### Iterate EXIF Fields with Walker Source: https://context7.com/rwcarlsen/goexif/llms.txt Uses the Walker interface to iterate over all EXIF tags in an image. This is useful for dynamic processing or dumping metadata into custom structures. ```go package main import ( "encoding/json" "github.com/rwcarlsen/goexif/exif" "github.com/rwcarlsen/goexif/tiff" ) type MetadataCollector struct { Fields map[string]interface{} } func (mc MetadataCollector) Walk(name exif.FieldName, tag *tiff.Tag) error { data, _ := tag.MarshalJSON() mc.Fields[string(name)] = json.RawMessage(data) return nil } ``` -------------------------------- ### Serialize EXIF Data to JSON Source: https://context7.com/rwcarlsen/goexif/llms.txt Converts all EXIF fields into a JSON string by implementing the json.Marshaler interface, facilitating easy integration with web services or data pipelines. ```go package main import ( "encoding/json" "fmt" "os" "github.com/rwcarlsen/goexif/exif" ) func main() { f, _ := os.Open("photo.jpg") defer f.Close() x, _ := exif.Decode(f) jsonData, _ := json.MarshalIndent(x, "", " ") fmt.Println(string(jsonData)) } ``` -------------------------------- ### Extract Photo Creation Timestamp Source: https://context7.com/rwcarlsen/goexif/llms.txt Retrieves the creation date of a photo using the DateTime() method. This automatically handles the logic of checking DateTimeOriginal and falling back to DateTime, returning a standard time.Time object. ```go package main import ( "fmt" "log" "os" "github.com/rwcarlsen/goexif/exif" ) func main() { f, _ := os.Open("photo.jpg") defer f.Close() x, _ := exif.Decode(f) tm, err := x.DateTime() if err != nil { if exif.IsTagNotPresentError(err) { log.Println("No date/time information in EXIF") } else { log.Printf("Error parsing date: %v", err) } return } fmt.Printf("Photo taken: %s\n", tm.Format("2006-01-02 15:04:05")) fmt.Printf("Unix timestamp: %d\n", tm.Unix()) } ``` -------------------------------- ### Extract GPS Coordinates with GoExif Source: https://context7.com/rwcarlsen/goexif/llms.txt Extracts latitude and longitude from an image's EXIF data. It handles various GPS formats and returns decimal degrees as float64 values. ```go package main import ( "fmt" "log" "os" "github.com/rwcarlsen/goexif/exif" ) func main() { f, _ := os.Open("geotagged_photo.jpg") defer f.Close() x, _ := exif.Decode(f) lat, long, err := x.LatLong() if err != nil { if exif.IsTagNotPresentError(err) { log.Println("No GPS data in image") } else { log.Printf("Error parsing GPS: %v", err) } return } fmt.Printf("Latitude: %.6f\n", lat) fmt.Printf("Longitude: %.6f\n", long) } ``` -------------------------------- ### Extracting EXIF Tag Values Source: https://context7.com/rwcarlsen/goexif/llms.txt Illustrates various methods available on the tiff.Tag type to extract data in specific formats, including StringVal, Int, Int64, Rat, and Rat2. These methods provide type-safe access to EXIF metadata fields. ```go package main import ( "fmt" "os" "github.com/rwcarlsen/goexif/exif" ) func main() { f, _ := os.Open("photo.jpg") defer f.Close() x, _ := exif.Decode(f) if tag, err := x.Get(exif.Make); err == nil { val, _ := tag.StringVal() fmt.Printf("Make (string): %s\n", val) } if tag, err := x.Get(exif.Orientation); err == nil { val, _ := tag.Int(0) fmt.Printf("Orientation (int): %d\n", val) } if tag, err := x.Get(exif.PixelXDimension); err == nil { val, _ := tag.Int64(0) fmt.Printf("Width (int64): %d\n", val) } if tag, err := x.Get(exif.FNumber); err == nil { num, denom, _ := tag.Rat2(0) fmt.Printf("F-Number: f/%.1f (%d/%d)\n", float64(num)/float64(denom), num, denom) } if tag, err := x.Get(exif.ExposureTime); err == nil { rat, _ := tag.Rat(0) f, _ := rat.Float64() fmt.Printf("Exposure: %.4f sec\n", f) } } ``` -------------------------------- ### Exif.MarshalJSON Source: https://context7.com/rwcarlsen/goexif/llms.txt Serializes all EXIF fields to JSON format. ```APIDOC ## GET Exif.MarshalJSON ### Description Serializes all EXIF fields to JSON format, implementing the json.Marshaler interface. ### Method Internal Method (Go Library) ### Endpoint json.Marshal(x) ### Response - **jsonData** ([]byte) - JSON representation of the EXIF metadata ``` -------------------------------- ### Tag Value Extraction Methods Source: https://context7.com/rwcarlsen/goexif/llms.txt Methods provided by the tiff.Tag type to extract metadata values into appropriate Go types. ```APIDOC ## Tag Value Methods ### Description The tiff.Tag type provides multiple methods for extracting values in different formats: Int, Int64, Float, Rat, Rat2, and StringVal. Each method is appropriate for specific EXIF data types. ### Methods - **StringVal()** - Returns the tag value as a string. - **Int(index int)** - Returns the tag value as an integer. - **Int64(index int)** - Returns the tag value as a 64-bit integer. - **Rat2(index int)** - Returns the tag value as a numerator and denominator (rational). - **Rat(index int)** - Returns the tag value as a *big.Rat for high-precision arithmetic. - **Format()** - Returns the underlying data type of the tag. ### Response Example ```go // Example: Extracting F-Number num, denom, _ := tag.Rat2(0) // Output: 28/10 ``` ``` -------------------------------- ### Exif.LatLong Source: https://context7.com/rwcarlsen/goexif/llms.txt Extracts GPS coordinates from the image's EXIF data as decimal degrees. ```APIDOC ## GET Exif.LatLong ### Description Extracts GPS coordinates from the image's EXIF data. Returns latitude and longitude as float64 values in decimal degrees. ### Method Internal Method (Go Library) ### Endpoint x.LatLong() ### Response - **lat** (float64) - Latitude in decimal degrees - **long** (float64) - Longitude in decimal degrees - **err** (error) - Error object, use exif.IsTagNotPresentError(err) to check for missing data ``` -------------------------------- ### Extract Embedded JPEG Thumbnail Source: https://context7.com/rwcarlsen/goexif/llms.txt Retrieves the embedded preview image from EXIF data. This allows for quick access to a thumbnail without decoding the full image. ```go package main import ( "os" "github.com/rwcarlsen/goexif/exif" ) func main() { f, _ := os.Open("photo.jpg") defer f.Close() x, _ := exif.Decode(f) thumbData, err := x.JpegThumbnail() if err == nil { thumbFile, _ := os.Create("thumbnail.jpg") defer thumbFile.Close() thumbFile.Write(thumbData) } } ``` -------------------------------- ### tiff.Decode Source: https://context7.com/rwcarlsen/goexif/llms.txt Parses raw TIFF data into a structured format, allowing for low-level access to IFDs and tags. ```APIDOC ## tiff.Decode ### Description Low-level TIFF structure decoder that parses raw TIFF data and returns the directory structure. Useful for direct TIFF manipulation or deep inspection of image metadata. ### Method Function Call ### Parameters #### Arguments - **r** (io.Reader) - Required - The reader containing the raw TIFF data. ### Response #### Success Response (200) - **t** (*tiff.Tiff) - The decoded TIFF structure containing byte order and IFD directories. - **err** (error) - Returns an error if decoding fails. ``` -------------------------------- ### Exif.JpegThumbnail Source: https://context7.com/rwcarlsen/goexif/llms.txt Extracts the embedded JPEG thumbnail from the EXIF data. ```APIDOC ## GET Exif.JpegThumbnail ### Description Extracts the embedded JPEG thumbnail from the EXIF data if present. ### Method Internal Method (Go Library) ### Endpoint x.JpegThumbnail() ### Response - **thumbData** ([]byte) - The raw binary data of the JPEG thumbnail - **err** (error) - Error object, returns error if no thumbnail is present ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.