• Posted by Peter Haza
  • On April 24, 2008

  • Filed under PHP

  • 3 Comments

Working with image meta data in Exif and IPTC headers from PHP

Writing IPTC IIM/headers

The most difficult part with IPTC is writing the headers. While iptcparse() unpacks the binary data, iptcembed() doesn’t automatically pack it. Fortunately the author of the iptc* functions (Thies C. Arntzen) made a user function to pack this. (Although I wonder why it wasn’t put into iptcembed()):

// Function to format the new IPTC text
// (thanks to Thies C. Arntzen)
function iptc_maketag($rec,$dat,$val){
    $len = strlen($val);
    if ($len < 0x8000)
        return chr(0x1c).chr($rec).chr($dat).
        chr($len >> 8).
        chr($len & 0xff).
        $val;
    else
        return chr(0x1c).chr($rec).chr($dat).
        chr(0x80).chr(0x04).
        chr(($len >> 24) & 0xff).
        chr(($len >> 16) & 0xff).
        chr(($len >> 8 ) & 0xff).
        chr(($len ) & 0xff).
        $val;
}

Not exactly well documented, but the parameters are like this:

$rec: Application record. (We’re working with #2)
$dat: Index. (120 for caption, 115 for contact. See the IPTC IIM specification)
$val: Value/data/text. Make sure this is within the length constraints of the IPTC IIM specification

This will return an IPTC binary block that we can embed into an image with iptcembed(). iptcembed() will return a full image binary string with the iptc block, and we will have to write that to a file.

$caption_block = iptc_maketag(2, 120, 'This is my caption');
$image_string = iptcembed($caption_block,
                'untouched_old_image.jpg');
file_put_contents('new_file_with_iptc.jpg', $image_string);

Now new_file_with_iptc.jpg is the same image as untouched_old_image.jpg, just with the iptc block written.

There you go. I’m impressed if you read all three pages, but now you’re set to work with images with Exif and IPTC embedded. Hope you enjoyed it.

Pages: 1 2 3

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

3 comments

  1. Posted by Shay 25th April, 2008 at 05:19 pm |

    another awesome article. Keep them coming, I’m learning lots from your site :)

  2. Posted by Brad 23rd September, 2009 at 10:20 pm |

    I want to make a webpage Gallery of a Directory of JPEGs (on my LINUX/Apache host), showing the above THUMBNAILs… via a web page, much like OSX or WIN shows thumbs of image files in Directories on my local comp.

  3. Posted by Anh Nguyen 19th July, 2010 at 07:05 am |

    Very nice article! By the way, do you know anyway to modify the exif of an image with PHP?

What do you think? Join the discussion...