c12e71cfc042a3206f55d42773333836edcc5301
[yaffs-website] / vendor / lsolesen / pel / src / PelJpeg.php
1 <?php
2
3 /**
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.
7  *
8  * Copyright (C) 2004, 2005, 2006, 2007 Martin Geisler.
9  *
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.
14  *
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.
19  *
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
24  */
25
26 namespace lsolesen\pel;
27
28 /**
29  * Class for handling JPEG data.
30  *
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}.
35  *
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:
40  *
41  * <code>
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();
48  * </code>
49  *
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}.
53  *
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.
59  *
60  * @author Martin Geisler <mgeisler@users.sourceforge.net>
61  * @package PEL
62  */
63 class PelJpeg
64 {
65
66     /**
67      * The sections in the JPEG data.
68      *
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.
75      *
76      * The content can be either generic {@link PelJpegContent JPEG
77      * content} or {@link PelExif Exif data}.
78      *
79      * @var array
80      */
81     private $sections = array();
82
83     /**
84      * The JPEG image data.
85      *
86      * @var PelDataWindow
87      */
88     private $jpeg_data = null;
89
90     /**
91      * Construct a new JPEG object.
92      *
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
96      * resource handle.
97      *
98      * New Exif data (in the form of a {@link PelExif} object) can be
99      * inserted with the {@link setExif()} method:
100      *
101      * <code>
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);
108      * </code>
109      *
110      * @param
111      *            mixed the data that this JPEG. This can either be a
112      *            filename, a {@link PelDataWindow} object, or a PHP image resource
113      *            handle.
114      */
115     public function __construct($data = false)
116     {
117         if ($data === false) {
118             return;
119         }
120
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.');
126             $this->load($data);
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));
130         } else {
131             throw new PelInvalidArgumentException('Bad type for $data: %s', gettype($data));
132         }
133     }
134
135     /**
136      * JPEG sections start with 0xFF. The first byte that is not
137      * 0xFF is a marker (hopefully).
138      *
139      * @param PelDataWindow $d
140      *
141      * @return integer
142      */
143     protected static function getJpgSectionStart($d)
144     {
145         for ($i = 0; $i < 7; $i ++) {
146             if ($d->getByte($i) != 0xFF) {
147                  break;
148             }
149         }
150         return $i;
151     }
152
153     /**
154      * Load data into a JPEG object.
155      *
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.
159      *
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.
165      *
166      * @param
167      *            PelDataWindow the data that will be turned into JPEG
168      *            sections.
169      */
170     public function load(PelDataWindow $d)
171     {
172         Pel::debug('Parsing %d bytes...', $d->getSize());
173
174         /* JPEG data is stored in big-endian format. */
175         $d->setByteOrder(PelConvert::BIG_ENDIAN);
176
177         /*
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.
182          */
183         while ($d->getSize() > 0) {
184             $i = $this->getJpgSectionStart($d);
185
186             $marker = $d->getByte($i);
187
188             if (!PelJpegMarker::isValid($marker)) {
189                 throw new PelJpegInvalidMarkerException($marker, $i);
190             }
191
192             /*
193              * Move window so first byte becomes first byte in this
194              * section.
195              */
196             $d->setWindowStart($i + 1);
197
198             if ($marker == PelJpegMarker::SOI || $marker == PelJpegMarker::EOI) {
199                 $content = new PelJpegContent(new PelDataWindow());
200                 $this->appendSection($marker, $content);
201             } else {
202                 /*
203                  * Read the length of the section. The length includes the
204                  * two bytes used to store the length.
205                  */
206                 $len = $d->getShort(0) - 2;
207
208                 Pel::debug('Found %s section of length %d', PelJpegMarker::getName($marker), $len);
209
210                 /* Skip past the length. */
211                 $d->setWindowStart(2);
212
213                 if ($marker == PelJpegMarker::APP1) {
214                     try {
215                         $content = new PelExif();
216                         $content->load($d->getClone(0, $len));
217                     } catch (PelInvalidDataException $e) {
218                         /*
219                          * We store the data as normal JPEG content if it could
220                          * not be parsed as Exif data.
221                          */
222                         $content = new PelJpegContent($d->getClone(0, $len));
223                     }
224
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);
233                 } else {
234                     $content = new PelJpegContent($d->getClone(0, $len));
235                     $this->appendSection($marker, $content);
236                     /* Skip past the data. */
237                     $d->setWindowStart($len);
238
239                     /* In case of SOS, image data will follow. */
240                     if ($marker == PelJpegMarker::SOS) {
241                         /*
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.
246                          */
247
248                         $length = $d->getSize();
249                         while ($d->getByte($length - 2) != 0xFF || $d->getByte($length - 1) != PelJpegMarker::EOI) {
250                             $length --;
251                         }
252
253                         $this->jpeg_data = $d->getClone(0, $length - 2);
254                         Pel::debug('JPEG data: ' . $this->jpeg_data->__toString());
255
256                         /* Append the EOI. */
257                         $this->appendSection(PelJpegMarker::EOI, new PelJpegContent(new PelDataWindow()));
258
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));
263                             /*
264                              * We don't have a proper JPEG marker for trailing
265                              * garbage, so we just use 0x00...
266                              */
267                             $this->appendSection(0x00, $content);
268                         }
269
270                         /* Done with the loop. */
271                         break;
272                     }
273                 }
274             }
275         } /* while ($d->getSize() > 0) */
276     }
277
278     /**
279      * Load data from a file into a JPEG object.
280      *
281      * @param
282      *            string the filename. This must be a readable file.
283      */
284     public function loadFile($filename)
285     {
286         $this->load(new PelDataWindow(file_get_contents($filename)));
287     }
288
289     /**
290      * Set Exif data.
291      *
292      * Use this to set the Exif data in the image. This will overwrite
293      * any old Exif information in the image.
294      *
295      * @param
296      *            PelExif the Exif data.
297      */
298     public function setExif(PelExif $exif)
299     {
300         $app0_offset = 1;
301         $app1_offset = - 1;
302
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) {
308                     $app0_offset = $i;
309                 } elseif ($this->sections[$i][0] == PelJpegMarker::APP1) {
310                     $app1_offset = $i;
311                     break;
312                 }
313             }
314         }
315
316         /*
317          * Store the Exif data at the appropriate place, either where the
318          * old Exif data was stored ($app1_offset) or right after APP0
319          * ($app0_offset+1).
320          */
321         if ($app1_offset > 0) {
322             $this->sections[$app1_offset][1] = $exif;
323         } else {
324             $this->insertSection(PelJpegMarker::APP1, $exif, $app0_offset + 1);
325         }
326     }
327
328     /**
329      * Set ICC data.
330      *
331      * Use this to set the ICC data in the image. This will overwrite
332      * any old ICC information in the image.
333      *
334      * @param
335      *            PelJpegContent the ICC data.
336      */
337     public function setICC(PelJpegContent $icc)
338     {
339         $app1_offset = 1;
340         $app2_offset = - 1;
341
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) {
347                     $app1_offset = $i;
348                 } elseif ($this->sections[$i][0] == PelJpegMarker::APP2) {
349                     $app2_offset = $i;
350                     break;
351                 }
352             }
353         }
354
355         /*
356          * Store the Exif data at the appropriate place, either where the
357          * old Exif data was stored ($app1_offset) or right after APP0
358          * ($app0_offset+1).
359          */
360         if ($app2_offset > 0) {
361             $this->sections[$app1_offset][1] = $icc;
362         } else {
363             $this->insertSection(PelJpegMarker::APP2, $icc, $app1_offset + 1);
364         }
365     }
366
367     /**
368      * Get Exif data.
369      *
370      * Use this to get the @{link PelExif Exif data} stored.
371      *
372      * @return PelExif the Exif data found or null if the image has no
373      *         Exif data.
374      */
375     public function getExif()
376     {
377         $exif = $this->getSection(PelJpegMarker::APP1);
378         if ($exif instanceof PelExif) {
379             return $exif;
380         }
381         return null;
382     }
383
384     /**
385      * Get ICC data.
386      *
387      * Use this to get the @{link PelJpegContent ICC data} stored.
388      *
389      * @return PelJpegContent the ICC data found or null if the image has no
390      *         ICC data.
391      */
392     public function getICC()
393     {
394         $icc = $this->getSection(PelJpegMarker::APP2);
395         if ($icc instanceof PelJpegContent) {
396             return $icc;
397         }
398         return null;
399     }
400
401     /**
402      * Clear any Exif data.
403      *
404      * This method will only clear the first @{link PelJpegMarker::APP1}
405      * section found (there should normally be just one).
406      */
407     public function clearExif()
408     {
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]);
413                 return;
414             }
415         }
416     }
417
418     /**
419      * Append a new section.
420      *
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.
424      *
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.
428      *
429      * @param
430      *            PelJpegMarker the marker identifying the new section.
431      *
432      * @param
433      *            PelJpegContent the content of the new section.
434      */
435     public function appendSection($marker, PelJpegContent $content)
436     {
437         $this->sections[] = array(
438             $marker,
439             $content
440         );
441     }
442
443     /**
444      * Insert a new section.
445      *
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.
449      *
450      * @param
451      *            PelJpegMarker the marker for the new section.
452      *
453      * @param
454      *            PelJpegContent the content of the new section.
455      *
456      * @param
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.
460      */
461     public function insertSection($marker, PelJpegContent $content, $offset)
462     {
463         array_splice($this->sections, $offset, 0, array(
464             array(
465                 $marker,
466                 $content
467             )
468         ));
469     }
470
471     /**
472      * Get a section corresponding to a particular marker.
473      *
474      * Please use the {@link getExif()} if you just need the Exif data.
475      *
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:
482      *
483      * <code>
484      * $dht3 = $jpeg->getSection(PelJpegMarker::DHT, 2);
485      * </code>
486      *
487      * @param
488      *            PelJpegMarker the marker identifying the section.
489      *
490      * @param
491      *            int the number of sections to be skipped. This must be a
492      *            non-negative integer.
493      *
494      * @return PelJpegContent the content found, or null if there is no
495      *         content available.
496      */
497     public function getSection($marker, $skip = 0)
498     {
499         foreach ($this->sections as $s) {
500             if ($s[0] == $marker) {
501                 if ($skip > 0) {
502                     $skip --;
503                 } else {
504                     return $s[1];
505                 }
506             }
507         }
508
509         return null;
510     }
511
512     /**
513      * Get all sections.
514      *
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
519      *         array of arrays.
520      *
521      *         So to loop through all the sections in a given JPEG image do
522      *         this:
523      *
524      *         <code>
525      *         foreach ($jpeg->getSections() as $section) {
526      *         $marker = $section[0];
527      *         $content = $section[1];
528      *         // Use $marker and $content here.
529      *         }
530      *         </code>
531      *
532      *         instead of this:
533      *
534      *         <code>
535      *         foreach ($jpeg->getSections() as $marker => $content) {
536      *         // Does not work the way you would think...
537      *         }
538      *         </code>
539      *
540      *         The problem is that there could be several sections with the same
541      *         marker, and thus a simple associative array does not suffice.
542      */
543     public function getSections()
544     {
545         return $this->sections;
546     }
547
548     /**
549      * Turn this JPEG object into bytes.
550      *
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
553      * method to do this.
554      *
555      * @return string bytes representing this JPEG object, including all
556      *         its sections and their associated data.
557      */
558     public function getBytes()
559     {
560         $bytes = '';
561
562         foreach ($this->sections as $section) {
563             $m = $section[0];
564             $c = $section[1];
565
566             /* Write the marker */
567             $bytes .= "\xFF" . PelJpegMarker::getBytes($m);
568             /* Skip over empty markers. */
569             if ($m == PelJpegMarker::SOI || $m == PelJpegMarker::EOI) {
570                 continue;
571             }
572
573             $data = $c->getBytes();
574             $size = strlen($data) + 2;
575
576             $bytes .= PelConvert::shortToBytes($size, PelConvert::BIG_ENDIAN);
577             $bytes .= $data;
578
579             /* In case of SOS, we need to write the JPEG data. */
580             if ($m == PelJpegMarker::SOS) {
581                 $bytes .= $this->jpeg_data->getBytes();
582             }
583         }
584
585         return $bytes;
586     }
587
588     /**
589      * Save the JPEG object as a JPEG image in a file.
590      *
591      * @param
592      *            string the filename to save in. An existing file with the
593      *            same name will be overwritten!
594      *
595      * @return integer|FALSE The number of bytes that were written to the
596      *         file, or FALSE on failure.
597      */
598     public function saveFile($filename)
599     {
600         return file_put_contents($filename, $this->getBytes());
601     }
602
603     /**
604      * Make a string representation of this JPEG object.
605      *
606      * This is mainly usefull for debugging. It will show the structure
607      * of the image, and its sections.
608      *
609      * @return string debugging information about this JPEG object.
610      */
611     public function __toString()
612     {
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));
620
621             if ($m == PelJpegMarker::SOI || $m == PelJpegMarker::EOI) {
622                 continue;
623             }
624
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());
630             } else {
631                 $str .= Pel::tra("  Content    : Unknown\n");
632             }
633         }
634
635         return $str;
636     }
637
638     /**
639      * Test data to see if it could be a valid JPEG image.
640      *
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.
645      *
646      * @param
647      *            PelDataWindow the bytes that will be checked.
648      *
649      * @return boolean true if the bytes look like the beginning of a
650      *         JPEG image, false otherwise.
651      *
652      * @see PelTiff::isValid()
653      */
654     public static function isValid(PelDataWindow $d)
655     {
656         /* JPEG data is stored in big-endian format. */
657         $d->setByteOrder(PelConvert::BIG_ENDIAN);
658
659         $i = self::getJpgSectionStart($d);
660
661         return $d->getByte($i) == PelJpegMarker::SOI;
662     }
663 }