2
0

Png.php 17 KB

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