PageRenderTime 97ms CodeModel.GetById 31ms app.highlight 17ms RepoModel.GetById 33ms app.codeStats 12ms

/library/Zend/Pdf/Resource/Image/Png.php

https://bitbucket.org/baruffaldi/website-2008-computer-shopping-3
PHP | 359 lines | 223 code | 54 blank | 82 comment | 21 complexity | 38945edc6e69433d4d0a82f0af66d55e MD5 | raw file
  1<?php
  2/**
  3 * Zend Framework
  4 *
  5 * LICENSE
  6 *
  7 * This source file is subject to the new BSD license that is bundled
  8 * with this package in the file LICENSE.txt.
  9 * It is also available through the world-wide-web at this URL:
 10 * http://framework.zend.com/license/new-bsd
 11 * If you did not receive a copy of the license and are unable to
 12 * obtain it through the world-wide-web, please send an email
 13 * to license@zend.com so we can send you a copy immediately.
 14 *
 15 * @package    Zend_Pdf
 16 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 17 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 18 */
 19
 20
 21/** Zend_Pdf_Resource_Image */
 22require_once 'Zend/Pdf/Resource/Image.php';
 23
 24/** Zend_Pdf_Exception */
 25require_once 'Zend/Pdf/Exception.php';
 26
 27/** Zend_Pdf_Element_Numeric */
 28require_once 'Zend/Pdf/Element/Numeric.php';
 29
 30/** Zend_Pdf_Element_Name */
 31require_once 'Zend/Pdf/Element/Name.php';
 32
 33/** Zend_Pdf_ElementFactory */
 34require_once 'Zend/Pdf/ElementFactory.php';
 35
 36
 37/**
 38 * PNG image
 39 *
 40 * @package    Zend_Pdf
 41 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 42 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 43 */
 44class Zend_Pdf_Resource_Image_Png extends Zend_Pdf_Resource_Image
 45{
 46    const PNG_COMPRESSION_DEFAULT_STRATEGY = 0;
 47    const PNG_COMPRESSION_FILTERED = 1;
 48    const PNG_COMPRESSION_HUFFMAN_ONLY = 2;
 49    const PNG_COMPRESSION_RLE = 3;
 50
 51    const PNG_FILTER_NONE = 0;
 52    const PNG_FILTER_SUB = 1;
 53    const PNG_FILTER_UP = 2;
 54    const PNG_FILTER_AVERAGE = 3;
 55    const PNG_FILTER_PAETH = 4;
 56
 57    const PNG_INTERLACING_DISABLED = 0;
 58    const PNG_INTERLACING_ENABLED = 1;
 59
 60    const PNG_CHANNEL_GRAY = 0;
 61    const PNG_CHANNEL_RGB = 2;
 62    const PNG_CHANNEL_INDEXED = 3;
 63    const PNG_CHANNEL_GRAY_ALPHA = 4;
 64    const PNG_CHANNEL_RGB_ALPHA = 6;
 65
 66    protected $_width;
 67    protected $_height;
 68    protected $_imageProperties;
 69
 70    /**
 71     * Object constructor
 72     *
 73     * @param string $imageFileName
 74     * @throws Zend_Pdf_Exception
 75     * @todo Add compression conversions to support compression strategys other than PNG_COMPRESSION_DEFAULT_STRATEGY.
 76     * @todo Add pre-compression filtering.
 77     * @todo Add interlaced image handling.
 78     * @todo Add support for 16-bit images. Requires PDF version bump to 1.5 at least.
 79     * @todo Add processing for all PNG chunks defined in the spec. gAMA etc.
 80     * @todo Fix tRNS chunk support for Indexed Images to a SMask.
 81     */
 82    public function __construct($imageFileName)
 83    {
 84        if (($imageFile = @fopen($imageFileName, 'rb')) === false ) {
 85            throw new Zend_Pdf_Exception( "Can not open '$imageFileName' file for reading." );
 86        }
 87
 88        parent::__construct();
 89
 90        //Check if the file is a PNG
 91        fseek($imageFile, 1, SEEK_CUR); //First signature byte (%)
 92        if ('PNG' != fread($imageFile, 3)) {
 93            throw new Zend_Pdf_Exception('Image is not a PNG');
 94        }
 95        fseek($imageFile, 12, SEEK_CUR); //Signature bytes (Includes the IHDR chunk) IHDR processed linerarly because it doesnt contain a variable chunk length
 96        $wtmp = unpack('Ni',fread($imageFile, 4)); //Unpack a 4-Byte Long
 97        $width = $wtmp['i'];
 98        $htmp = unpack('Ni',fread($imageFile, 4));
 99        $height = $htmp['i'];
100        $bits = ord(fread($imageFile, 1)); //Higher than 8 bit depths are only supported in later versions of PDF.
101        $color = ord(fread($imageFile, 1));
102
103        $compression = ord(fread($imageFile, 1));
104        $prefilter = ord(fread($imageFile,1));
105
106        if (($interlacing = ord(fread($imageFile,1))) != Zend_Pdf_Resource_Image_Png::PNG_INTERLACING_DISABLED) {
107            throw new Zend_Pdf_Exception( "Only non-interlaced images are currently supported." );
108        }
109
110        $this->_width = $width;
111        $this->_height = $height;
112        $this->_imageProperties = array();
113        $this->_imageProperties['bitDepth'] = $bits;
114        $this->_imageProperties['pngColorType'] = $color;
115        $this->_imageProperties['pngFilterType'] = $prefilter;
116        $this->_imageProperties['pngCompressionType'] = $compression;
117        $this->_imageProperties['pngInterlacingType'] = $interlacing;
118
119        fseek($imageFile, 4, SEEK_CUR); //4 Byte Ending Sequence
120        $imageData = '';
121
122        /*
123         * The following loop processes PNG chunks. 4 Byte Longs are packed first give the chunk length
124         * followed by the chunk signature, a four byte code. IDAT and IEND are manditory in any PNG.
125         */
126        while(($chunkLengthBytes = fread($imageFile, 4)) !== false) {
127            $chunkLengthtmp         = unpack('Ni', $chunkLengthBytes);
128            $chunkLength            = $chunkLengthtmp['i'];
129            $chunkType                      = fread($imageFile, 4);
130            switch($chunkType) {
131                case 'IDAT': //Image Data
132                    /*
133                     * Reads the actual image data from the PNG file. Since we know at this point that the compression
134                     * strategy is the default strategy, we also know that this data is Zip compressed. We will either copy
135                     * the data directly to the PDF and provide the correct FlateDecode predictor, or decompress the data
136                     * decode the filters and output the data as a raw pixel map.
137                     */
138                    $imageData .= fread($imageFile, $chunkLength);
139                    fseek($imageFile, 4, SEEK_CUR);
140                    break;
141
142                case 'PLTE': //Palette
143                    $paletteData = fread($imageFile, $chunkLength);
144                    fseek($imageFile, 4, SEEK_CUR);
145                    break;
146
147                case 'tRNS': //Basic (non-alpha channel) transparency.
148                    $trnsData = fread($imageFile, $chunkLength);
149                    switch ($color) {
150                        case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY:
151                            $baseColor = ord(substr($trnsData, 1, 1));
152                            $transparencyData = array(new Zend_Pdf_Element_Numeric($baseColor), new Zend_Pdf_Element_Numeric($baseColor));
153                            break;
154
155                        case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB:
156                            $red = ord(substr($trnsData,1,1));
157                            $green = ord(substr($trnsData,3,1));
158                            $blue = ord(substr($trnsData,5,1));
159                            $transparencyData = array(new Zend_Pdf_Element_Numeric($red), new Zend_Pdf_Element_Numeric($red), new Zend_Pdf_Element_Numeric($green), new Zend_Pdf_Element_Numeric($green), new Zend_Pdf_Element_Numeric($blue), new Zend_Pdf_Element_Numeric($blue));
160                            break;
161
162                        case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_INDEXED:
163                            //Find the first transparent color in the index, we will mask that. (This is a bit of a hack. This should be a SMask and mask all entries values).
164                            if(($trnsIdx = strpos($trnsData, chr(0))) !== false) {
165                                $transparencyData = array(new Zend_Pdf_Element_Numeric($trnsIdx), new Zend_Pdf_Element_Numeric($trnsIdx));
166                            }
167                            break;
168
169                        case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY_ALPHA:
170                            // Fall through to the next case
171
172                        case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB_ALPHA:
173                            throw new Zend_Pdf_Exception( "tRNS chunk illegal for Alpha Channel Images" );
174                            break;
175                    }
176                    fseek($imageFile, 4, SEEK_CUR); //4 Byte Ending Sequence
177                    break;
178
179                case 'IEND';
180                    break 2; //End the loop too
181
182                default:
183                    fseek($imageFile, $chunkLength + 4, SEEK_CUR); //Skip the section
184                    break;
185            }
186        }
187        fclose($imageFile);
188
189        $compressed = true;
190        $imageDataTmp = '';
191        $smaskData = '';
192        switch ($color) {
193            case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB:
194                $colorSpace = new Zend_Pdf_Element_Name('DeviceRGB');
195                break;
196
197            case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY:
198                $colorSpace = new Zend_Pdf_Element_Name('DeviceGray');
199                break;
200
201            case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_INDEXED:
202                if(empty($paletteData)) {
203                    throw new Zend_Pdf_Exception( "PNG Corruption: No palette data read for indexed type PNG." );
204                }
205                $colorSpace = new Zend_Pdf_Element_Array();
206                $colorSpace->items[] = new Zend_Pdf_Element_Name('Indexed');
207                $colorSpace->items[] = new Zend_Pdf_Element_Name('DeviceRGB');
208                $colorSpace->items[] = new Zend_Pdf_Element_Numeric((strlen($paletteData)/3-1));
209                $paletteObject = $this->_objectFactory->newObject(new Zend_Pdf_Element_String_Binary($paletteData));
210                $colorSpace->items[] = $paletteObject;
211                break;
212
213            case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_GRAY_ALPHA:
214                /*
215                 * To decode PNG's with alpha data we must create two images from one. One image will contain the Gray data
216                 * the other will contain the Gray transparency overlay data. The former will become the object data and the latter
217                 * will become the Shadow Mask (SMask).
218                 */
219                if($bits > 8) {
220                    throw new Zend_Pdf_Exception("Alpha PNGs with bit depth > 8 are not yet supported");
221                }
222
223                $colorSpace = new Zend_Pdf_Element_Name('DeviceGray');
224
225                $decodingObjFactory = Zend_Pdf_ElementFactory::createFactory(1);
226                $decodingStream = $decodingObjFactory->newStreamObject($imageData);
227                $decodingStream->dictionary->Filter      = new Zend_Pdf_Element_Name('FlateDecode');
228                $decodingStream->dictionary->DecodeParms = new Zend_Pdf_Element_Dictionary();
229                $decodingStream->dictionary->DecodeParms->Predictor        = new Zend_Pdf_Element_Numeric(15);
230                $decodingStream->dictionary->DecodeParms->Columns          = new Zend_Pdf_Element_Numeric($width);
231                $decodingStream->dictionary->DecodeParms->Colors           = new Zend_Pdf_Element_Numeric(2);   //GreyAlpha
232                $decodingStream->dictionary->DecodeParms->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits);
233                $decodingStream->skipFilters();
234
235                $pngDataRawDecoded = $decodingStream->value;
236
237                //Iterate every pixel and copy out gray data and alpha channel (this will be slow)
238                for($pixel = 0, $pixelcount = ($width * $height); $pixel < $pixelcount; $pixel++) {
239                    $imageDataTmp .= $pngDataRawDecoded[($pixel*2)];
240                    $smaskData .= $pngDataRawDecoded[($pixel*2)+1];
241                }
242                $compressed = false;
243                $imageData  = $imageDataTmp; //Overwrite image data with the gray channel without alpha
244                break;
245
246            case Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB_ALPHA:
247                /*
248                 * To decode PNG's with alpha data we must create two images from one. One image will contain the RGB data
249                 * the other will contain the Gray transparency overlay data. The former will become the object data and the latter
250                 * will become the Shadow Mask (SMask).
251                 */
252                if($bits > 8) {
253                    throw new Zend_Pdf_Exception("Alpha PNGs with bit depth > 8 are not yet supported");
254                }
255
256                $colorSpace = new Zend_Pdf_Element_Name('DeviceRGB');
257
258                $decodingObjFactory = Zend_Pdf_ElementFactory::createFactory(1);
259                $decodingStream = $decodingObjFactory->newStreamObject($imageData);
260                $decodingStream->dictionary->Filter      = new Zend_Pdf_Element_Name('FlateDecode');
261                $decodingStream->dictionary->DecodeParms = new Zend_Pdf_Element_Dictionary();
262                $decodingStream->dictionary->DecodeParms->Predictor        = new Zend_Pdf_Element_Numeric(15);
263                $decodingStream->dictionary->DecodeParms->Columns          = new Zend_Pdf_Element_Numeric($width);
264                $decodingStream->dictionary->DecodeParms->Colors           = new Zend_Pdf_Element_Numeric(4);   //RGBA
265                $decodingStream->dictionary->DecodeParms->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits);
266                $decodingStream->skipFilters();
267
268                $pngDataRawDecoded = $decodingStream->value;
269
270                //Iterate every pixel and copy out rgb data and alpha channel (this will be slow)
271                for($pixel = 0, $pixelcount = ($width * $height); $pixel < $pixelcount; $pixel++) {
272                    $imageDataTmp .= $pngDataRawDecoded[($pixel*4)+0] . $pngDataRawDecoded[($pixel*4)+1] . $pngDataRawDecoded[($pixel*4)+2];
273                    $smaskData .= $pngDataRawDecoded[($pixel*4)+3];
274                }
275
276                $compressed = false;
277                $imageData  = $imageDataTmp; //Overwrite image data with the RGB channel without alpha
278                break;
279
280            default:
281                throw new Zend_Pdf_Exception( "PNG Corruption: Invalid color space." );
282        }
283
284        if(empty($imageData)) {
285            throw new Zend_Pdf_Exception( "Corrupt PNG Image. Mandatory IDAT chunk not found." );
286        }
287
288        $imageDictionary = $this->_resource->dictionary;
289        if(!empty($smaskData)) {
290            /*
291             * Includes the Alpha transparency data as a Gray Image, then assigns the image as the Shadow Mask for the main image data.
292             */
293            $smaskStream = $this->_objectFactory->newStreamObject($smaskData);
294            $smaskStream->dictionary->Type = new Zend_Pdf_Element_Name('XObject');
295            $smaskStream->dictionary->Subtype = new Zend_Pdf_Element_Name('Image');
296            $smaskStream->dictionary->Width = new Zend_Pdf_Element_Numeric($width);
297            $smaskStream->dictionary->Height = new Zend_Pdf_Element_Numeric($height);
298            $smaskStream->dictionary->ColorSpace = new Zend_Pdf_Element_Name('DeviceGray');
299            $smaskStream->dictionary->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits);
300            $imageDictionary->SMask = $smaskStream;
301
302            // Encode stream with FlateDecode filter
303            $smaskStreamDecodeParms = array();
304            $smaskStreamDecodeParms['Predictor']        = new Zend_Pdf_Element_Numeric(15);
305            $smaskStreamDecodeParms['Columns']          = new Zend_Pdf_Element_Numeric($width);
306            $smaskStreamDecodeParms['Colors']           = new Zend_Pdf_Element_Numeric(1);
307            $smaskStreamDecodeParms['BitsPerComponent'] = new Zend_Pdf_Element_Numeric(8);
308            $smaskStream->dictionary->DecodeParms  = new Zend_Pdf_Element_Dictionary($smaskStreamDecodeParms);
309            $smaskStream->dictionary->Filter       = new Zend_Pdf_Element_Name('FlateDecode');
310        }
311
312        if(!empty($transparencyData)) {
313            //This is experimental and not properly tested.
314            $imageDictionary->Mask = new Zend_Pdf_Element_Array($transparencyData);
315        }
316
317        $imageDictionary->Width            = new Zend_Pdf_Element_Numeric($width);
318        $imageDictionary->Height           = new Zend_Pdf_Element_Numeric($height);
319        $imageDictionary->ColorSpace       = $colorSpace;
320        $imageDictionary->BitsPerComponent = new Zend_Pdf_Element_Numeric($bits);
321        $imageDictionary->Filter       = new Zend_Pdf_Element_Name('FlateDecode');
322
323        $decodeParms = array();
324        $decodeParms['Predictor']        = new Zend_Pdf_Element_Numeric(15); // Optimal prediction
325        $decodeParms['Columns']          = new Zend_Pdf_Element_Numeric($width);
326        $decodeParms['Colors']           = new Zend_Pdf_Element_Numeric((($color==Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB || $color==Zend_Pdf_Resource_Image_Png::PNG_CHANNEL_RGB_ALPHA)?(3):(1)));
327        $decodeParms['BitsPerComponent'] = new Zend_Pdf_Element_Numeric($bits);
328        $imageDictionary->DecodeParms  = new Zend_Pdf_Element_Dictionary($decodeParms);
329
330        //Include only the image IDAT section data.
331        $this->_resource->value = $imageData;
332
333        //Skip double compression
334        if ($compressed) {
335            $this->_resource->skipFilters();
336        }
337    }
338
339    /**
340     * Image width
341     */
342    public function getPixelWidth() {
343    return $this->_width;
344    }
345
346    /**
347     * Image height
348     */
349    public function getPixelHeight() {
350        return $this->_height;
351    }
352
353    /**
354     * Image properties
355     */
356    public function getProperties() {
357        return $this->_imageProperties;
358    }
359}