Png.php 17 KB

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