How to extract metadata (e.g., EXIF data) from an image in Go?

To extract metadata such as EXIF data from an image in Go, you can use the github.com/rwcarlsen/goexif/exif package. Here's an example of how you can achieve this:

  1. Install the goexif package by running the following command:
go get github.com/rwcarlsen/goexif/exif
  1. Create a Go file, e.g., main.go, and import the necessary packages:
package main import ( "fmt" "log" "os" "github.com/rwcarlsen/goexif/exif" )
  1. Define a function that extracts and prints the metadata from an image:
func extractMetadata(imagePath string) { file, err := os.Open(imagePath) if err != nil { log.Fatal(err) } defer file.Close() exifData, err := exif.Decode(file) if err != nil { log.Fatal(err) } // Extract specific metadata fields using exifData.Get method camModel, _ := exifData.Get(exif.Model) imageWidth, _ := exifData.Get(exif.ImageWidth) imageHeight, _ := exifData.Get(exif.ImageLength) fmt.Println("Camera Model:", camModel.String()) fmt.Println("Image Width:", imageWidth.String()) fmt.Println("Image Height:", imageHeight.String()) }
  1. In the main function, call the extractMetadata function with the path to your image:
func main() { imagePath := "path/to/your/image.jpg" extractMetadata(imagePath) }
  1. Build and run the Go program:
go build main.go ./main

The program will extract the EXIF data from the specified image and print the camera model, image width, and image height. You can modify the extractMetadata function to extract other desired metadata fields based on your requirements.