PageRenderTime 49ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

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

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