BxDolImageResize.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
  4. * CC-BY License - http://creativecommons.org/licenses/by/3.0/
  5. *
  6. * @defgroup DolphinCore Dolphin Core
  7. * @{
  8. */
  9. // Function error codes
  10. define( 'IMAGE_ERROR_SUCCESS', 0 );
  11. define( 'IMAGE_ERROR_SOURCE_NOT_EXISTS', 1 );
  12. define( 'IMAGE_ERROR_WRONG_TYPE', 2 );
  13. define( 'IMAGE_ERROR_FILE_OPEN_FAILED', 3 );
  14. define( 'IMAGE_ERROR_IMAGEMAGICK_ERROR', 4 );
  15. define( 'IMAGE_ERROR_GD_NOT_INSTALLED', 5 );
  16. define( 'IMAGE_ERROR_GD_TYPE_NOT_SUPPORTED', 6 );
  17. define( 'IMAGE_ERROR_GD_OPEN_FAILED', 7 );
  18. define( 'IMAGE_ERROR_GD_RESIZE_ERROR', 8 );
  19. define( 'IMAGE_ERROR_GD_MERGE_ERROR', 9 );
  20. define( 'IMAGE_ERROR_GD_WRITE_FAILED', 10 );
  21. define( 'IMAGE_ERROR_GD_TTF_NOT_SUPPORTED', 11 );
  22. define( 'IMAGE_ERROR_GD_FILTER_ERROR', 12 );
  23. // Image types for GD
  24. // NOTE: actually these constants exist in PHP >= 4.3.0, but they are included for
  25. // back compatibility
  26. define( 'IMAGE_TYPE_GIF', 1 );
  27. define( 'IMAGE_TYPE_JPG', 2 );
  28. define( 'IMAGE_TYPE_PNG', 3 );
  29. class BxDolImageResize extends BxDol implements iBxDolSingleton {
  30. var $w = 64, $h = 64; ///< size of destination image
  31. var $_isCrop = false;
  32. var $_isAutoCrop = false;
  33. var $_cropX, $_cropY, $_cropW, $_cropH;
  34. var $_iForceOutputType = false; ///< force IMAGE_TYPE_PNG, IMAGE_TYPE_PNG, IMAGE_TYPE_GIF or false to keep the original format // TODO: check if this setting works when ImageMagick is used
  35. var $_iJpegQuality = 90; ///< jpeg quality
  36. var $_isSquareResize = false; ///< use smart resize, destination image will be exact Width x Height size
  37. var $_isUseGD; ///< use GD library or command line ImagMagic utilites
  38. function BxDolImageResize() {
  39. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  40. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  41. parent::BxDol();
  42. $this->_isUseGD = getParam('enable_gd') == 'on' && extension_loaded('gd') ? true : false;
  43. }
  44. /**
  45. * Prevent cloning the instance
  46. */
  47. public function __clone() {
  48. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  49. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  50. }
  51. /**
  52. * Get singleton instance of the class
  53. */
  54. public static function getInstance() {
  55. if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
  56. $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolImageResize();
  57. return $GLOBALS['bxDolClasses'][__CLASS__];
  58. }
  59. function isAllowedImage ($sPath) {
  60. if ($this->_isUseGD) {
  61. $aImage = getimagesize($sPath);
  62. if (!empty($aImage) && in_array($aImage[2], array(1, 2, 3)))
  63. return true;
  64. } else {
  65. // TODO: image checking using image magick
  66. }
  67. return false;
  68. }
  69. function resize ($mixedImage, $sDstImage = '') {
  70. if (is_array($mixedImage)) {
  71. $aRet = array();
  72. foreach ($mixedImage as $s) {
  73. $aRet[] = $this->_resize ($s, $s);
  74. }
  75. return $aRet;
  76. } else {
  77. return $this->_resize ($mixedImage, $sDstImage);
  78. }
  79. }
  80. function applyWatermark ($mixedImage, $sDstImage, $wtrFilename, $wtrTransparency) {
  81. if (is_array($mixedImage)) {
  82. $aRet = array();
  83. foreach ($mixedImage as $s) {
  84. $aRet[] = $this->_applyWatermark ($s, $s, $wtrFilename, $wtrTransparency);
  85. }
  86. return $aRet;
  87. } else {
  88. return $this->_applyWatermark ($mixedImage, $sDstImage, $wtrFilename, $wtrTransparency);
  89. }
  90. }
  91. function grayscale ($mixedImage, $sDstImage = '') {
  92. if (is_array($mixedImage)) {
  93. $aRet = array();
  94. foreach ($mixedImage as $s) {
  95. $aRet[] = $this->_grayscale ($s, $s);
  96. }
  97. return $aRet;
  98. } else {
  99. return $this->_grayscale ($mixedImage, $sDstImage);
  100. }
  101. }
  102. function setSize ($w, $h) {
  103. $this->w = $w;
  104. $this->h = $h;
  105. }
  106. function removeCropOptions () {
  107. $this->_isCrop = false;
  108. $this->_isAutoCrop = false;
  109. }
  110. function setCropOptions ($x, $y, $w, $h) {
  111. $this->_isCrop = true;
  112. $this->_cropX = $x;
  113. $this->_cropY = $y;
  114. $this->_cropW = $w;
  115. $this->_cropH = $h;
  116. }
  117. /**
  118. * Crop image to destination size with filling whole area of destination size
  119. */
  120. function setAutoCrop ($b) {
  121. $this->_isAutoCrop = $b;
  122. }
  123. function setJpegOutput ($b) {
  124. $this->setOutputType($b ? IMAGE_TYPE_JPG : false);
  125. }
  126. function setOutputType ($iType) {
  127. $this->_iForceOutputType = $iType;;
  128. }
  129. function setJpegQuality ($i) {
  130. $this->_iJpegQuality = $i;
  131. }
  132. function setSquareResize ($b) {
  133. $this->_isSquareResize = ($b ? true : false);
  134. }
  135. function isUsedGD () {
  136. return $this->_isUseGD;
  137. }
  138. function getImageSize($sPath) {
  139. $aSize = getimagesize($sPath);
  140. return array ('w' => $aSize[0], 'h' => $aSize[1]);
  141. }
  142. // private functions are below -------------------------------
  143. function _grayscale ($sSrcImage, $sDstImage = '') {
  144. if (!file_exists($sSrcImage))
  145. return IMAGE_ERROR_SOURCE_NOT_EXISTS;
  146. if (!$sDstImage)
  147. $sDstImage = $sSrcImage;
  148. if ($sDstImage == $sSrcImage) {
  149. chmod($sDstImage, 0666);
  150. }
  151. return $this->_isUseGD ? $this->_grayscaleGD ($sSrcImage, $sDstImage) : $this->_grayscaleImageMagick ($sSrcImage, $sDstImage);
  152. }
  153. function _grayscaleGD ($sSrcImage, $sDstImage) {
  154. $iErr = 0;
  155. $src_im =& $this->_createGDImage($sSrcImage, $size, $iErr);
  156. $sizeOrig = $size;
  157. if ($iErr)
  158. return $iErr;
  159. if (!$src_im)
  160. return IMAGE_ERROR_GD_OPEN_FAILED;
  161. if (!imagefilter($src_im, IMG_FILTER_GRAYSCALE))
  162. return IMAGE_ERROR_GD_FILTER_ERROR;
  163. $writeResult = $this->_writeImageGD ($src_im, $sDstImage, $size[2]);
  164. // free memory
  165. imagedestroy( $src_im );
  166. if ( $writeResult && file_exists($sDstImage) )
  167. return IMAGE_ERROR_SUCCESS;
  168. return IMAGE_ERROR_GD_WRITE_FAILED;
  169. }
  170. function _grayscaleImageMagick ($sSrcImage, $sDstImage) {
  171. $cmd = "{$GLOBALS['CONVERT']} \"$sSrcImage\" -type Grayscale -quantize Gray \"$sDstImage\"";
  172. @exec( $cmd );
  173. if ( file_exists($sDstImage) )
  174. return IMAGE_ERROR_SUCCESS;
  175. return IMAGE_ERROR_IMAGEMAGICK_ERROR;
  176. }
  177. function _resize ($sSrcImage, $sDstImage = '') {
  178. if (!file_exists($sSrcImage))
  179. return IMAGE_ERROR_SOURCE_NOT_EXISTS;
  180. if (!$sDstImage)
  181. $sDstImage = $sSrcImage;
  182. if ($sDstImage == $sSrcImage) {
  183. chmod($sDstImage, 0666);
  184. }
  185. return $this->_isUseGD ? $this->_resizeGD ($sSrcImage, $sDstImage) : $this->_resizeImageMagick ($sSrcImage, $sDstImage);
  186. }
  187. function _resizeGD ($sSrcImage, $sDstImage) {
  188. $iErr = 0;
  189. $src_im =& $this->_createGDImage($sSrcImage, $size, $iErr);
  190. $sizeOrig = $size;
  191. if ($iErr)
  192. return $iErr;
  193. if (!$src_im)
  194. return IMAGE_ERROR_GD_OPEN_FAILED;
  195. $xd = $yd = 0;
  196. $xs = $ys = 0;
  197. if ($this->_isAutoCrop) {
  198. $sourceRatio = (float) ($size[0] / $size[1]);
  199. $destRatio = (float) ($this->w / $this->h);
  200. if ( $sourceRatio > $destRatio )
  201. $resizeRatio = (float) ($this->h / $size[1]);
  202. else
  203. $resizeRatio = (float) ($this->w / $size[0]);
  204. $destW = (int) ($resizeRatio * $size[0]);
  205. $destH = (int) ($resizeRatio * $size[1]);
  206. if ($destW > $this->w)
  207. $this->setCropOptions (floor(($size[0] - $this->w/$resizeRatio)/2.0), 0, floor($this->w/$resizeRatio), $size[1]);
  208. elseif ($destH > $this->h)
  209. $this->setCropOptions (0, floor(($size[1] - $this->h/$resizeRatio)/2.0), $size[0], floor($this->h/$resizeRatio));
  210. }
  211. if ($this->_isCrop) {
  212. $size[0] = $this->_cropW;
  213. $size[1] = $this->_cropH;
  214. $xs = $this->_cropX;
  215. $ys = $this->_cropY;
  216. $destW = $this->w;
  217. $destH = $this->h;
  218. } elseif ($this->_isSquareResize) {
  219. $destW = $this->w;
  220. $destH = $this->h;
  221. if ($size[0] < $size[1]) {
  222. $d = ($size[1] - $size[0])/2;
  223. $size[1] = $size[0];
  224. $xs = 0;
  225. $ys = (int)$d;
  226. } else {
  227. $d = ($size[0] - $size[1])/2;
  228. $size[0] = $size[1];
  229. $xs = (int)$d;
  230. $ys = 0;
  231. }
  232. } else {
  233. // determ destination size
  234. $sourceRatio = (float) ($size[0] / $size[1]);
  235. $destRatio = (float) ($this->w / $this->h);
  236. if ( $sourceRatio > $destRatio )
  237. $resizeRatio = (float) ($this->w / $size[0]);
  238. else
  239. $resizeRatio = (float) ($this->h / $size[1]);
  240. $destW = (int) ($resizeRatio * $size[0]);
  241. $destH = (int) ($resizeRatio * $size[1]);
  242. }
  243. // this is more qualitative function, but it doesn't exist in old GD and doesn't support GIF format
  244. if ( function_exists( 'imagecreatetruecolor' ) && $size[2] != IMAGE_TYPE_GIF )
  245. {
  246. // resize only if size is larger than needed
  247. if ( $this->_isCrop || $sizeOrig[0] > $this->w || $sizeOrig[1] > $this->h )
  248. {
  249. $dst_im = imagecreatetruecolor( $destW, $destH );
  250. imagecolortransparent($dst_im, imagecolorallocate($dst_im, 0, 0, 0));
  251. imagealphablending($dst_im, false);
  252. imagesavealpha($dst_im, true);
  253. $convertResult = imagecopyresampled( $dst_im, $src_im, $xd, $yd, $xs, $ys,
  254. $destW, $destH, $size[0], $size[1] );
  255. }
  256. else
  257. {
  258. $dst_im = $src_im;
  259. $convertResult = true;
  260. }
  261. }
  262. else // this is for old GD versions and for GIF images
  263. {
  264. // resize only if size is larger than needed
  265. if ( $size[0] > $this->w || $size[1] > $this->h )
  266. {
  267. $dst_im = imagecreate( $destW, $destH );
  268. if ($size[2] == IMAGE_TYPE_GIF) {
  269. ImageColorTransparent( $dst_im, imagecolorallocate($dst_im, 0, 0, 0) );
  270. imagealphablending( $dst_im, false );
  271. }
  272. $convertResult = imagecopyresized( $dst_im, $src_im, $xd, $yd, $xs, $ys,
  273. $destW, $destH, $size[0], $size[1] );
  274. }
  275. else
  276. {
  277. $dst_im = $src_im;
  278. $convertResult = true;
  279. }
  280. }
  281. if ( !$convertResult )
  282. return IMAGE_ERROR_GD_RESIZE_ERROR;
  283. $writeResult = $this->_writeImageGD ($dst_im, $sDstImage, $size[2]);
  284. // free memory
  285. if ( $dst_im != $src_im )
  286. {
  287. imagedestroy( $src_im );
  288. imagedestroy( $dst_im );
  289. }
  290. else
  291. {
  292. imagedestroy( $src_im );
  293. }
  294. if ( $writeResult && file_exists($sDstImage) )
  295. return IMAGE_ERROR_SUCCESS;
  296. return IMAGE_ERROR_GD_WRITE_FAILED;
  297. }
  298. function _resizeImageMagick ($sSrcImage, $sDstImage) {
  299. // TODO: $this->_isCrop and $this->_isSquareResize
  300. if ( $sSrcImage == $sDstImage )
  301. {
  302. $cmd = "{$GLOBALS['MOGRIFY']} -geometry {$this->w}\">\"x{$this->h}\">\" \"$sSrcImage\"";
  303. @exec( $cmd );
  304. $ext = strrchr($sSrcImage, '.');
  305. $nameWithoutExt = substr( $sSrcImage, 0, strrpos($sSrcImage, '.') );
  306. if ( file_exists( "{$nameWithoutExt}.mgk" ) )
  307. rename( "{$nameWithoutExt}.mgk", $sSrcImage );
  308. }
  309. else
  310. {
  311. $cmd = "{$GLOBALS['CONVERT']} \"$sSrcImage\" -geometry {$this->w}\">\"x{$this->h}\">\" \"$sDstImage\"";
  312. @exec( $cmd );
  313. }
  314. if ( file_exists($sDstImage) )
  315. return IMAGE_ERROR_SUCCESS;
  316. return IMAGE_ERROR_IMAGEMAGICK_ERROR;
  317. }
  318. function _applyWatermark( $srcFilename, $dstFilename, $wtrFilename, $wtrTransparency )
  319. {
  320. // TODO: watermard are not applied correctly, becuase images of different suzes are used, FIX IT
  321. // input validation
  322. $wtrTransparency = (int) $wtrTransparency;
  323. if ( $wtrTransparency > 100 )
  324. $wtrTransparency = 100;
  325. if ( !file_exists( $srcFilename ) )
  326. return IMAGE_ERROR_SOURCE_NOT_EXISTS;
  327. if ( !file_exists( $wtrFilename ) )
  328. return IMAGE_ERROR_SOURCE_NOT_EXISTS;
  329. // if destination and source filenames are equivalent then change mode for destination
  330. if ( $srcFilename == $dstFilename )
  331. chmod( $dstFilename, 0666 );
  332. if ( $this->_isUseGD )
  333. {
  334. return $this->_applyWatermarkGD($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency);
  335. }
  336. else
  337. {
  338. return $this->_applyWatermarkImageMagick($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency);
  339. }
  340. }
  341. function _applyWatermarkGD($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency) {
  342. $iErr = 0;
  343. $src_im =& $this->_createGDImage($srcFilename, $size, $iErr);
  344. if ($iErr)
  345. return $iErr;
  346. if (!$src_im)
  347. return IMAGE_ERROR_GD_OPEN_FAILED;
  348. $wtr_im =& $this->_createGDImage($wtrFilename, $wtrSize, $iErr);
  349. if ($iErr)
  350. return $iErr;
  351. if (!$wtr_im )
  352. return IMAGE_ERROR_GD_OPEN_FAILED;
  353. if (function_exists('imagecreatetruecolor'))
  354. $dst_im = imagecreatetruecolor( $size[0], $size[1] );
  355. else
  356. $dst_im = imagecreate( $size[0], $size[1] );
  357. $watermarkX = ($size[0] - $wtrSize[0]) / 2;
  358. $watermarkY = $size[1] - $wtrSize[1];
  359. $copyResult = imagecopy( $dst_im, $src_im, 0, 0, 0, 0, $size[0], $size[1]);
  360. if (!$copyResult)
  361. return IMAGE_ERROR_GD_MERGE_ERROR;
  362. imagealphablending($wtr_im, false);
  363. imagesavealpha($wtr_im, true);
  364. if (IMAGE_TYPE_PNG == $wtrSize[2] && imageistruecolor($wtr_im))
  365. $mergeResult = imagecopy ( $dst_im, $wtr_im, $watermarkX, $watermarkY, 0, 0, $wtrSize[0], $wtrSize[1]);
  366. else
  367. $mergeResult = imagecopymerge ( $dst_im, $wtr_im, $watermarkX, $watermarkY, 0, 0, $wtrSize[0], $wtrSize[1], $wtrTransparency );
  368. if ( !$mergeResult )
  369. return IMAGE_ERROR_GD_MERGE_ERROR;
  370. switch ( $size[2] )
  371. {
  372. case IMAGE_TYPE_GIF:
  373. $writeResult = imagegif( $dst_im, $dstFilename );
  374. break;
  375. case IMAGE_TYPE_JPG:
  376. $writeResult = imagejpeg( $dst_im, $dstFilename, $this->_iJpegQuality);
  377. break;
  378. case IMAGE_TYPE_PNG:
  379. $writeResult = imagepng( $dst_im, $dstFilename );
  380. break;
  381. }
  382. // free memory
  383. imagedestroy( $dst_im );
  384. imagedestroy( $src_im );
  385. imagedestroy( $wtr_im );
  386. if ( $writeResult )
  387. return IMAGE_ERROR_SUCCESS;
  388. else
  389. return IMAGE_ERROR_GD_WRITE_FAILED;
  390. }
  391. function _applyWatermarkImageMagick($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency) {
  392. $imgTransparency = 100 - $wtrTransparency;
  393. $cmd = "{$GLOBALS['COMPOSITE']} -gravity \"South\" -dissolve \"$imgTransparency\" \"$wtrFilename\" -dissolve $wtrTransparency \"$srcFilename\" \"$dstFilename\"";
  394. @exec( $cmd );
  395. if ( file_exists($dstFilename) )
  396. return IMAGE_ERROR_SUCCESS;
  397. return IMAGE_ERROR_IMAGEMAGICK_ERROR;
  398. }
  399. function & _createGDImage($s, &$aSize, &$iErr) {
  400. if (!isset($this->gdInfoArray))
  401. $this->gdInfoArray = gd_info();
  402. $aSize = getimagesize($s);
  403. // only GIF, JPG and PNG allowed
  404. switch ( $aSize[2] )
  405. {
  406. case IMAGE_TYPE_GIF:
  407. if (!isset($this->gdInfoArray['GIF Read Support']) || !$this->gdInfoArray['GIF Read Support'] || !isset($this->gdInfoArray['GIF Create Support']) || !$this->gdInfoArray['GIF Create Support'])
  408. return ($iErr = IMAGE_ERROR_GD_TYPE_NOT_SUPPORTED);
  409. $r = imagecreatefromgif( $s );
  410. return $r;
  411. case IMAGE_TYPE_JPG:
  412. if ((!isset($this->gdInfoArray['JPG Support']) || !$this->gdInfoArray['JPG Support']) && (!isset($this->gdInfoArray['JPEG Support']) || !$this->gdInfoArray['JPEG Support']))
  413. return ($iErr = IMAGE_ERROR_GD_TYPE_NOT_SUPPORTED);
  414. $r = imagecreatefromjpeg( $s );
  415. return $r;
  416. case IMAGE_TYPE_PNG:
  417. if (!isset($this->gdInfoArray['PNG Support']) || !$this->gdInfoArray['PNG Support'])
  418. return ($iErr = IMAGE_ERROR_GD_TYPE_NOT_SUPPORTED);
  419. $r = imagecreatefrompng( $s );
  420. return $r;
  421. default:
  422. return ($iErr = IMAGE_ERROR_WRONG_TYPE);
  423. }
  424. }
  425. function _writeImageGD ($src_im, $sDstImage, $iSrcImageType) {
  426. $writeResult = false;
  427. switch ($this->_iForceOutputType){
  428. case IMAGE_TYPE_JPG:
  429. $writeResult = imagejpeg( $src_im, $sDstImage, $this->_iJpegQuality);
  430. break;
  431. case IMAGE_TYPE_PNG:
  432. $writeResult = imagepng( $src_im, $sDstImage);
  433. break;
  434. case IMAGE_TYPE_GIF:
  435. $writeResult = imagegif( $src_im, $sDstImage );
  436. break;
  437. default:
  438. switch ($iSrcImageType) {
  439. case IMAGE_TYPE_GIF:
  440. $writeResult = imagegif( $src_im, $sDstImage );
  441. break;
  442. case IMAGE_TYPE_PNG:
  443. $writeResult = imagepng( $src_im, $sDstImage );
  444. break;
  445. case IMAGE_TYPE_JPG:
  446. default:
  447. $writeResult = imagejpeg( $src_im, $sDstImage, $this->_iJpegQuality);
  448. break;
  449. }
  450. }
  451. return $writeResult;
  452. }
  453. }
  454. /** @} */