I\'m trying to create a website where I can add and modify metadata within a JPEG file.
Is there a way in which I can write the exif data in a fairly easy way.
Imagick does let you set EXIF-data but only to objects in memory, when writing the file to disk these data is simply ignored. The most popular solution is to either shell out to exiftools or use the PHP-library PEL. The documentation of PEL is sparse, and the API is not really self-explanatory either.
I came across this problem when trying to add the correct EXIF-data to images that would be uploaded as 360 images to Facebook, which requires specific camera make and model to be specified as EXIF. The code below will open an image file, set its make and model, and save back to disk. If you are looking to set other EXIF-data there is a complete list of all supported PelTag-constants here in the PEL docs.
$data = new PelDataWindow(file_get_contents('IMAGE PATH'));
$tiff = null;
$file = null;
// If it is a JPEG-image, check if EXIF-headers exists
if (PelJpeg::isValid($data)) {
$jpeg = $file = new PelJpeg();
$jpeg->load($data);
$exif = $jpeg->getExif();
// If no EXIF in image, create it
if($exif == null) {
$exif = new PelExif();
$jpeg->setExif($exif);
$tiff = new PelTiff();
$exif->setTiff($tiff);
}
else {
$tiff = $exif->getTiff();
}
}
// If it is a TIFF EXIF-headers will always be set
elseif (PelTiff::isValid($data)) {
$tiff = $file = new PelTiff();
$tiff->load($data);
}
else {
throw new \Exception('Invalid image format');
}
// Get the first Ifd, where most common EXIF-tags reside
$ifd0 = $tiff->getIfd();
// If no Ifd info found, create it
if($ifd0 == null) {
$ifd0 = new PelIfd(PelIfd::IFD0);
$tiff->setIfd($ifd0);
}
// See if the MAKE-tag already exists in Ifd
$make = $ifd0->getEntry(PelTag::MAKE);
// Create MAKE-tag if not found, otherwise just change the value
if($make == null) {
$make = new PelEntryAscii(PelTag::MAKE, 'RICOH');
$ifd0->addEntry($make);
}
else {
$make->setValue('RICOH');
}
// See if the MODEL-tag already exists in Ifd
$model = $ifd0->getEntry(PelTag::MODEL);
// Create MODEL-tag if not found, otherwise just change the value
if($model == null) {
$model = new PelEntryAscii(PelTag::MODEL, 'RICOH THETA S');
$ifd0->addEntry($model);
}
else {
$model->setValue('RICOH THETA S');
}
// Save to disk
$file->saveFile('IMAGE.jpg');