4 * PEL: PHP Exif Library.
5 * A library with support for reading and
6 * writing all Exif headers in JPEG and TIFF images using PHP.
8 * Copyright (C) 2004, 2005, 2006, 2007 Martin Geisler.
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program in the file COPYING; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
26 namespace lsolesen\pel;
29 * Class for handling JPEG data.
31 * The {@link PelJpeg} class defined here provides an abstraction for
32 * dealing with a JPEG file. The file will be contain a number of
33 * sections containing some {@link PelJpegContent content} identified
34 * by a {@link PelJpegMarker marker}.
36 * The {@link getExif()} method is used get hold of the {@link
37 * PelJpegMarker::APP1 APP1} section which stores Exif data. So if
38 * the name of the JPEG file is stored in $filename, then one would
39 * get hold of the Exif data by saying:
42 * $jpeg = new PelJpeg($filename);
43 * $exif = $jpeg->getExif();
44 * $tiff = $exif->getTiff();
45 * $ifd0 = $tiff->getIfd();
46 * $exif = $ifd0->getSubIfd(PelIfd::EXIF);
47 * $ifd1 = $ifd0->getNextIfd();
50 * The $idf0 and $ifd1 variables will then be two {@link PelTiff TIFF}
51 * {@link PelIfd Image File Directories}, in which the data is stored
52 * under the keys found in {@link PelTag}.
54 * Should one have some image data (in the form of a {@link
55 * PelDataWindow}) of an unknown type, then the {@link
56 * PelJpeg::isValid()} function is handy: it will quickly test if the
57 * data could be valid JPEG data. The {@link PelTiff::isValid()}
58 * function does the same for TIFF images.
60 * @author Martin Geisler <mgeisler@users.sourceforge.net>
67 * The sections in the JPEG data.
69 * A JPEG file is built up as a sequence of sections, each section
70 * is identified with a {@link PelJpegMarker}. Some sections can
71 * occur more than once in the JPEG stream (the {@link
72 * PelJpegMarker::DQT DQT} and {@link PelJpegMarker::DHT DTH}
73 * markers for example) and so this is an array of ({@link
74 * PelJpegMarker}, {@link PelJpegContent}) pairs.
76 * The content can be either generic {@link PelJpegContent JPEG
77 * content} or {@link PelExif Exif data}.
81 private $sections = array();
84 * The JPEG image data.
88 private $jpeg_data = null;
91 * Construct a new JPEG object.
93 * The new object will be empty unless an argument is given from
94 * which it can initialize itself. This can either be the filename
95 * of a JPEG image, a {@link PelDataWindow} object or a PHP image
98 * New Exif data (in the form of a {@link PelExif} object) can be
99 * inserted with the {@link setExif()} method:
102 * $jpeg = new PelJpeg($data);
103 * // Create container for the Exif information:
104 * $exif = new PelExif();
105 * // Now Add a PelTiff object with a PelIfd object with one or more
106 * // PelEntry objects to $exif... Finally add $exif to $jpeg:
107 * $jpeg->setExif($exif);
111 * mixed the data that this JPEG. This can either be a
112 * filename, a {@link PelDataWindow} object, or a PHP image resource
115 public function __construct($data = false)
117 if ($data === false) {
121 if (is_string($data)) {
122 Pel::debug('Initializing PelJpeg object from %s', $data);
123 $this->loadFile($data);
124 } elseif ($data instanceof PelDataWindow) {
125 Pel::debug('Initializing PelJpeg object from PelDataWindow.');
127 } elseif (is_resource($data) && get_resource_type($data) == 'gd') {
128 Pel::debug('Initializing PelJpeg object from image resource.');
129 $this->load(new PelDataWindow($data));
131 throw new PelInvalidArgumentException('Bad type for $data: %s', gettype($data));
136 * JPEG sections start with 0xFF. The first byte that is not
137 * 0xFF is a marker (hopefully).
139 * @param PelDataWindow $d
143 protected static function getJpgSectionStart($d)
145 for ($i = 0; $i < 7; $i ++) {
146 if ($d->getByte($i) != 0xFF) {
154 * Load data into a JPEG object.
156 * The data supplied will be parsed and turned into an object
157 * structure representing the image. This structure can then be
158 * manipulated and later turned back into an string of bytes.
160 * This methods can be called at any time after a JPEG object has
161 * been constructed, also after the {@link appendSection()} has been
162 * called to append custom sections. Loading several JPEG images
163 * into one object will accumulate the sections, but there will only
164 * be one {@link PelJpegMarker::SOS} section at any given time.
167 * PelDataWindow the data that will be turned into JPEG
170 public function load(PelDataWindow $d)
172 Pel::debug('Parsing %d bytes...', $d->getSize());
174 /* JPEG data is stored in big-endian format. */
175 $d->setByteOrder(PelConvert::BIG_ENDIAN);
178 * Run through the data to read the sections in the image. After
179 * each section is read, the start of the data window will be
180 * moved forward, and after the last section we'll terminate with
181 * no data left in the window.
183 while ($d->getSize() > 0) {
184 $i = $this->getJpgSectionStart($d);
186 $marker = $d->getByte($i);
188 if (!PelJpegMarker::isValid($marker)) {
189 throw new PelJpegInvalidMarkerException($marker, $i);
193 * Move window so first byte becomes first byte in this
196 $d->setWindowStart($i + 1);
198 if ($marker == PelJpegMarker::SOI || $marker == PelJpegMarker::EOI) {
199 $content = new PelJpegContent(new PelDataWindow());
200 $this->appendSection($marker, $content);
203 * Read the length of the section. The length includes the
204 * two bytes used to store the length.
206 $len = $d->getShort(0) - 2;
208 Pel::debug('Found %s section of length %d', PelJpegMarker::getName($marker), $len);
210 /* Skip past the length. */
211 $d->setWindowStart(2);
213 if ($marker == PelJpegMarker::APP1) {
215 $content = new PelExif();
216 $content->load($d->getClone(0, $len));
217 } catch (PelInvalidDataException $e) {
219 * We store the data as normal JPEG content if it could
220 * not be parsed as Exif data.
222 $content = new PelJpegContent($d->getClone(0, $len));
225 $this->appendSection($marker, $content);
226 /* Skip past the data. */
227 $d->setWindowStart($len);
228 } elseif ($marker == PelJpegMarker::COM) {
229 $content = new PelJpegComment();
230 $content->load($d->getClone(0, $len));
231 $this->appendSection($marker, $content);
232 $d->setWindowStart($len);
234 $content = new PelJpegContent($d->getClone(0, $len));
235 $this->appendSection($marker, $content);
236 /* Skip past the data. */
237 $d->setWindowStart($len);
239 /* In case of SOS, image data will follow. */
240 if ($marker == PelJpegMarker::SOS) {
242 * Some images have some trailing (garbage?) following the
243 * EOI marker. To handle this we seek backwards until we
244 * find the EOI marker. Any trailing content is stored as
245 * a PelJpegContent object.
248 $length = $d->getSize();
249 while ($d->getByte($length - 2) != 0xFF || $d->getByte($length - 1) != PelJpegMarker::EOI) {
253 $this->jpeg_data = $d->getClone(0, $length - 2);
254 Pel::debug('JPEG data: ' . $this->jpeg_data->__toString());
256 /* Append the EOI. */
257 $this->appendSection(PelJpegMarker::EOI, new PelJpegContent(new PelDataWindow()));
259 /* Now check to see if there are any trailing data. */
260 if ($length != $d->getSize()) {
261 Pel::maybeThrow(new PelException('Found trailing content ' . 'after EOI: %d bytes', $d->getSize() - $length));
262 $content = new PelJpegContent($d->getClone($length));
264 * We don't have a proper JPEG marker for trailing
265 * garbage, so we just use 0x00...
267 $this->appendSection(0x00, $content);
270 /* Done with the loop. */
275 } /* while ($d->getSize() > 0) */
279 * Load data from a file into a JPEG object.
282 * string the filename. This must be a readable file.
284 public function loadFile($filename)
286 $this->load(new PelDataWindow(file_get_contents($filename)));
292 * Use this to set the Exif data in the image. This will overwrite
293 * any old Exif information in the image.
296 * PelExif the Exif data.
298 public function setExif(PelExif $exif)
303 /* Search through all sections looking for APP0 or APP1. */
304 $sections_count = count($this->sections);
305 for ($i = 0; $i < $sections_count; $i ++) {
306 if (! empty($this->sections[$i][0])) {
307 if ($this->sections[$i][0] == PelJpegMarker::APP0) {
309 } elseif ($this->sections[$i][0] == PelJpegMarker::APP1) {
317 * Store the Exif data at the appropriate place, either where the
318 * old Exif data was stored ($app1_offset) or right after APP0
321 if ($app1_offset > 0) {
322 $this->sections[$app1_offset][1] = $exif;
324 $this->insertSection(PelJpegMarker::APP1, $exif, $app0_offset + 1);
331 * Use this to set the ICC data in the image. This will overwrite
332 * any old ICC information in the image.
335 * PelJpegContent the ICC data.
337 public function setICC(PelJpegContent $icc)
342 /* Search through all sections looking for APP0 or APP1. */
343 $count_sections = count($this->sections);
344 for ($i = 0; $i < $count_sections; $i ++) {
345 if (! empty($this->sections[$i][0])) {
346 if ($this->sections[$i][0] == PelJpegMarker::APP1) {
348 } elseif ($this->sections[$i][0] == PelJpegMarker::APP2) {
356 * Store the Exif data at the appropriate place, either where the
357 * old Exif data was stored ($app1_offset) or right after APP0
360 if ($app2_offset > 0) {
361 $this->sections[$app1_offset][1] = $icc;
363 $this->insertSection(PelJpegMarker::APP2, $icc, $app1_offset + 1);
370 * Use this to get the @{link PelExif Exif data} stored.
372 * @return PelExif the Exif data found or null if the image has no
375 public function getExif()
377 $exif = $this->getSection(PelJpegMarker::APP1);
378 if ($exif instanceof PelExif) {
387 * Use this to get the @{link PelJpegContent ICC data} stored.
389 * @return PelJpegContent the ICC data found or null if the image has no
392 public function getICC()
394 $icc = $this->getSection(PelJpegMarker::APP2);
395 if ($icc instanceof PelJpegContent) {
402 * Clear any Exif data.
404 * This method will only clear the first @{link PelJpegMarker::APP1}
405 * section found (there should normally be just one).
407 public function clearExif()
409 $sections_count = count($this->sections);
410 for ($i = 0; $i < $sections_count; $i ++) {
411 if ($this->sections[$i][0] == PelJpegMarker::APP1) {
412 unset($this->sections[$i]);
419 * Append a new section.
421 * Used only when loading an image. If it used again later, then the
422 * section will end up after the @{link PelJpegMarker::EOI EOI
423 * marker} and will probably not be useful.
425 * Please use @{link setExif()} instead if you intend to add Exif
426 * information to an image as that function will know the right
427 * place to insert the data.
430 * PelJpegMarker the marker identifying the new section.
433 * PelJpegContent the content of the new section.
435 public function appendSection($marker, PelJpegContent $content)
437 $this->sections[] = array(
444 * Insert a new section.
446 * Please use @{link setExif()} instead if you intend to add Exif
447 * information to an image as that function will know the right
448 * place to insert the data.
451 * PelJpegMarker the marker for the new section.
454 * PelJpegContent the content of the new section.
457 * int the offset where the new section will be inserted ---
458 * use 0 to insert it at the very beginning, use 1 to insert it
459 * between sections 1 and 2, etc.
461 public function insertSection($marker, PelJpegContent $content, $offset)
463 array_splice($this->sections, $offset, 0, array(
472 * Get a section corresponding to a particular marker.
474 * Please use the {@link getExif()} if you just need the Exif data.
476 * This will search through the sections of this JPEG object,
477 * looking for a section identified with the specified {@link
478 * PelJpegMarker marker}. The {@link PelJpegContent content} will
479 * then be returned. The optional argument can be used to skip over
480 * some of the sections. So if one is looking for the, say, third
481 * {@link PelJpegMarker::DHT DHT} section one would do:
484 * $dht3 = $jpeg->getSection(PelJpegMarker::DHT, 2);
488 * PelJpegMarker the marker identifying the section.
491 * int the number of sections to be skipped. This must be a
492 * non-negative integer.
494 * @return PelJpegContent the content found, or null if there is no
497 public function getSection($marker, $skip = 0)
499 foreach ($this->sections as $s) {
500 if ($s[0] == $marker) {
515 * @return array an array of ({@link PelJpegMarker}, {@link
516 * PelJpegContent}) pairs. Each pair is an array with the {@link
517 * PelJpegMarker} as the first element and the {@link
518 * PelJpegContent} as the second element, so the return type is an
521 * So to loop through all the sections in a given JPEG image do
525 * foreach ($jpeg->getSections() as $section) {
526 * $marker = $section[0];
527 * $content = $section[1];
528 * // Use $marker and $content here.
535 * foreach ($jpeg->getSections() as $marker => $content) {
536 * // Does not work the way you would think...
540 * The problem is that there could be several sections with the same
541 * marker, and thus a simple associative array does not suffice.
543 public function getSections()
545 return $this->sections;
549 * Turn this JPEG object into bytes.
551 * The bytes returned by this method is ready to be stored in a file
552 * as a valid JPEG image. Use the {@link saveFile()} convenience
555 * @return string bytes representing this JPEG object, including all
556 * its sections and their associated data.
558 public function getBytes()
562 foreach ($this->sections as $section) {
566 /* Write the marker */
567 $bytes .= "\xFF" . PelJpegMarker::getBytes($m);
568 /* Skip over empty markers. */
569 if ($m == PelJpegMarker::SOI || $m == PelJpegMarker::EOI) {
573 $data = $c->getBytes();
574 $size = strlen($data) + 2;
576 $bytes .= PelConvert::shortToBytes($size, PelConvert::BIG_ENDIAN);
579 /* In case of SOS, we need to write the JPEG data. */
580 if ($m == PelJpegMarker::SOS) {
581 $bytes .= $this->jpeg_data->getBytes();
589 * Save the JPEG object as a JPEG image in a file.
592 * string the filename to save in. An existing file with the
593 * same name will be overwritten!
595 * @return integer|FALSE The number of bytes that were written to the
596 * file, or FALSE on failure.
598 public function saveFile($filename)
600 return file_put_contents($filename, $this->getBytes());
604 * Make a string representation of this JPEG object.
606 * This is mainly usefull for debugging. It will show the structure
607 * of the image, and its sections.
609 * @return string debugging information about this JPEG object.
611 public function __toString()
613 $str = Pel::tra("Dumping JPEG data...\n");
614 $count_sections = count($this->sections);
615 for ($i = 0; $i < $count_sections; $i ++) {
616 $m = $this->sections[$i][0];
617 $c = $this->sections[$i][1];
618 $str .= Pel::fmt("Section %d (marker 0x%02X - %s):\n", $i, $m, PelJpegMarker::getName($m));
619 $str .= Pel::fmt(" Description: %s\n", PelJpegMarker::getDescription($m));
621 if ($m == PelJpegMarker::SOI || $m == PelJpegMarker::EOI) {
625 if ($c instanceof PelExif) {
626 $str .= Pel::tra(" Content : Exif data\n");
627 $str .= $c->__toString() . "\n";
628 } elseif ($c instanceof PelJpegComment) {
629 $str .= Pel::fmt(" Content : %s\n", $c->getValue());
631 $str .= Pel::tra(" Content : Unknown\n");
639 * Test data to see if it could be a valid JPEG image.
641 * The function will only look at the first few bytes of the data,
642 * and try to determine if it could be a valid JPEG image based on
643 * those bytes. This means that the check is more like a heuristic
644 * than a rigorous check.
647 * PelDataWindow the bytes that will be checked.
649 * @return boolean true if the bytes look like the beginning of a
650 * JPEG image, false otherwise.
652 * @see PelTiff::isValid()
654 public static function isValid(PelDataWindow $d)
656 /* JPEG data is stored in big-endian format. */
657 $d->setByteOrder(PelConvert::BIG_ENDIAN);
659 $i = self::getJpgSectionStart($d);
661 return $d->getByte($i) == PelJpegMarker::SOI;