BxDolImageResize.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. protected $w = 64, $h = 64; ///< size of destination image
  31. protected $_isCrop = false;
  32. protected $_isAutoCrop = false;
  33. protected $_cropX, $_cropY, $_cropW, $_cropH;
  34. protected $_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. protected $_iJpegQuality = 90; ///< jpeg quality
  36. protected $_isSquareResize = false; ///< use smart resize, destination image will be exact Width x Height size
  37. protected $_isUseGD; ///< use GD library or command line ImagMagic utilites
  38. function __construct() {
  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::__construct();
  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. if ($iErr)
  157. return $iErr;
  158. if (!$src_im)
  159. return IMAGE_ERROR_GD_OPEN_FAILED;
  160. if (!imagefilter($src_im, IMG_FILTER_GRAYSCALE))
  161. return IMAGE_ERROR_GD_FILTER_ERROR;
  162. $writeResult = $this->_writeImageGD ($src_im, $sDstImage, $size[2]);
  163. // free memory
  164. imagedestroy( $src_im );
  165. if ( $writeResult && file_exists($sDstImage) )
  166. return IMAGE_ERROR_SUCCESS;
  167. return IMAGE_ERROR_GD_WRITE_FAILED;
  168. }
  169. function _grayscaleImageMagick ($sSrcImage, $sDstImage) {
  170. $cmd = "{$GLOBALS['CONVERT']} \"$sSrcImage\" -type Grayscale -quantize Gray \"$sDstImage\"";
  171. @exec( $cmd );
  172. if ( file_exists($sDstImage) )
  173. return IMAGE_ERROR_SUCCESS;
  174. return IMAGE_ERROR_IMAGEMAGICK_ERROR;
  175. }
  176. function _resize ($sSrcImage, $sDstImage = '') {
  177. if (!file_exists($sSrcImage))
  178. return IMAGE_ERROR_SOURCE_NOT_EXISTS;
  179. if (!$sDstImage)
  180. $sDstImage = $sSrcImage;
  181. if ($sDstImage == $sSrcImage) {
  182. chmod($sDstImage, 0666);
  183. }
  184. return $this->_isUseGD ? $this->_resizeGD ($sSrcImage, $sDstImage) : $this->_resizeImageMagick ($sSrcImage, $sDstImage);
  185. }
  186. function _resizeGD ($sSrcImage, $sDstImage) {
  187. $iErr = 0;
  188. $src_im =& $this->_createGDImage($sSrcImage, $size, $iErr);
  189. $sizeOrig = $size;
  190. if ($iErr)
  191. return $iErr;
  192. if (!$src_im)
  193. return IMAGE_ERROR_GD_OPEN_FAILED;
  194. $xd = $yd = 0;
  195. $xs = $ys = 0;
  196. if ($this->_isAutoCrop) {
  197. $sourceRatio = (float) ($size[0] / $size[1]);
  198. $destRatio = (float) ($this->w / $this->h);
  199. if ( $sourceRatio > $destRatio )
  200. $resizeRatio = (float) ($this->h / $size[1]);
  201. else
  202. $resizeRatio = (float) ($this->w / $size[0]);
  203. $destW = (int) ($resizeRatio * $size[0]);
  204. $destH = (int) ($resizeRatio * $size[1]);
  205. if ($destW > $this->w)
  206. $this->setCropOptions (floor(($size[0] - $this->w/$resizeRatio)/2.0), 0, floor($this->w/$resizeRatio), $size[1]);
  207. elseif ($destH > $this->h)
  208. $this->setCropOptions (0, floor(($size[1] - $this->h/$resizeRatio)/2.0), $size[0], floor($this->h/$resizeRatio));
  209. }
  210. if ($this->_isCrop) {
  211. $size[0] = $this->_cropW;
  212. $size[1] = $this->_cropH;
  213. $xs = $this->_cropX;
  214. $ys = $this->_cropY;
  215. $destW = $this->w;
  216. $destH = $this->h;
  217. } elseif ($this->_isSquareResize) {
  218. $destW = $this->w;
  219. $destH = $this->h;
  220. if ($size[0] < $size[1]) {
  221. $d = ($size[1] - $size[0])/2;
  222. $size[1] = $size[0];
  223. $xs = 0;
  224. $ys = (int)$d;
  225. } else {
  226. $d = ($size[0] - $size[1])/2;
  227. $size[0] = $size[1];
  228. $xs = (int)$d;
  229. $ys = 0;
  230. }
  231. } else {
  232. // determ destination size
  233. $sourceRatio = (float) ($size[0] / $size[1]);
  234. $destRatio = (float) ($this->w / $this->h);
  235. if ( $sourceRatio > $destRatio )
  236. $resizeRatio = (float) ($this->w / $size[0]);
  237. else
  238. $resizeRatio = (float) ($this->h / $size[1]);
  239. $destW = (int) ($resizeRatio * $size[0]);
  240. $destH = (int) ($resizeRatio * $size[1]);
  241. }
  242. // this is more qualitative function, but it doesn't exist in old GD and doesn't support GIF format
  243. if ( function_exists( 'imagecreatetruecolor' ) && $size[2] != IMAGE_TYPE_GIF )
  244. {
  245. // resize only if size is larger than needed
  246. if ( $this->_isCrop || $sizeOrig[0] > $this->w || $sizeOrig[1] > $this->h )
  247. {
  248. $dst_im = imagecreatetruecolor( $destW, $destH );
  249. imagecolortransparent($dst_im, imagecolorallocate($dst_im, 0, 0, 0));
  250. imagealphablending($dst_im, false);
  251. imagesavealpha($dst_im, true);
  252. $convertResult = imagecopyresampled( $dst_im, $src_im, $xd, $yd, $xs, $ys,
  253. $destW, $destH, $size[0], $size[1] );
  254. }
  255. else
  256. {
  257. $dst_im = $src_im;
  258. $convertResult = true;
  259. }
  260. }
  261. else // this is for old GD versions and for GIF images
  262. {
  263. // resize only if size is larger than needed
  264. if ( $size[0] > $this->w || $size[1] > $this->h )
  265. {
  266. $dst_im = imagecreate( $destW, $destH );
  267. if ($size[2] == IMAGE_TYPE_GIF) {
  268. ImageColorTransparent( $dst_im, imagecolorallocate($dst_im, 0, 0, 0) );
  269. imagealphablending( $dst_im, false );
  270. }
  271. $convertResult = imagecopyresized( $dst_im, $src_im, $xd, $yd, $xs, $ys,
  272. $destW, $destH, $size[0], $size[1] );
  273. }
  274. else
  275. {
  276. $dst_im = $src_im;
  277. $convertResult = true;
  278. }
  279. }
  280. if ( !$convertResult )
  281. return IMAGE_ERROR_GD_RESIZE_ERROR;
  282. $writeResult = $this->_writeImageGD ($dst_im, $sDstImage, $size[2]);
  283. // free memory
  284. if ( $dst_im != $src_im )
  285. {
  286. imagedestroy( $src_im );
  287. imagedestroy( $dst_im );
  288. }
  289. else
  290. {
  291. imagedestroy( $src_im );
  292. }
  293. if ( $writeResult && file_exists($sDstImage) )
  294. return IMAGE_ERROR_SUCCESS;
  295. return IMAGE_ERROR_GD_WRITE_FAILED;
  296. }
  297. function _resizeImageMagick ($sSrcImage, $sDstImage) {
  298. // TODO: $this->_isCrop and $this->_isSquareResize
  299. if ( $sSrcImage == $sDstImage )
  300. {
  301. $cmd = "{$GLOBALS['MOGRIFY']} -geometry {$this->w}\">\"x{$this->h}\">\" \"$sSrcImage\"";
  302. @exec( $cmd );
  303. $nameWithoutExt = substr( $sSrcImage, 0, strrpos($sSrcImage, '.') );
  304. if ( file_exists( "{$nameWithoutExt}.mgk" ) )
  305. rename( "{$nameWithoutExt}.mgk", $sSrcImage );
  306. }
  307. else
  308. {
  309. $cmd = "{$GLOBALS['CONVERT']} \"$sSrcImage\" -geometry {$this->w}\">\"x{$this->h}\">\" \"$sDstImage\"";
  310. @exec( $cmd );
  311. }
  312. if ( file_exists($sDstImage) )
  313. return IMAGE_ERROR_SUCCESS;
  314. return IMAGE_ERROR_IMAGEMAGICK_ERROR;
  315. }
  316. function _applyWatermark( $srcFilename, $dstFilename, $wtrFilename, $wtrTransparency )
  317. {
  318. // TODO: watermard are not applied correctly, becuase images of different suzes are used, FIX IT
  319. // input validation
  320. $wtrTransparency = (int) $wtrTransparency;
  321. if ( $wtrTransparency > 100 )
  322. $wtrTransparency = 100;
  323. if ( !file_exists( $srcFilename ) )
  324. return IMAGE_ERROR_SOURCE_NOT_EXISTS;
  325. if ( !file_exists( $wtrFilename ) )
  326. return IMAGE_ERROR_SOURCE_NOT_EXISTS;
  327. // if destination and source filenames are equivalent then change mode for destination
  328. if ( $srcFilename == $dstFilename )
  329. chmod( $dstFilename, 0666 );
  330. if ( $this->_isUseGD )
  331. {
  332. return $this->_applyWatermarkGD($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency);
  333. }
  334. else
  335. {
  336. return $this->_applyWatermarkImageMagick($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency);
  337. }
  338. }
  339. function _applyWatermarkGD($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency) {
  340. $iErr = 0;
  341. $src_im =& $this->_createGDImage($srcFilename, $size, $iErr);
  342. if ($iErr)
  343. return $iErr;
  344. if (!$src_im)
  345. return IMAGE_ERROR_GD_OPEN_FAILED;
  346. $wtr_im =& $this->_createGDImage($wtrFilename, $wtrSize, $iErr);
  347. if ($iErr)
  348. return $iErr;
  349. if (!$wtr_im )
  350. return IMAGE_ERROR_GD_OPEN_FAILED;
  351. if (function_exists('imagecreatetruecolor'))
  352. $dst_im = imagecreatetruecolor( $size[0], $size[1] );
  353. else
  354. $dst_im = imagecreate( $size[0], $size[1] );
  355. $watermarkX = ($size[0] - $wtrSize[0]) / 2;
  356. $watermarkY = $size[1] - $wtrSize[1];
  357. $copyResult = imagecopy( $dst_im, $src_im, 0, 0, 0, 0, $size[0], $size[1]);
  358. if (!$copyResult)
  359. return IMAGE_ERROR_GD_MERGE_ERROR;
  360. imagealphablending($wtr_im, false);
  361. imagesavealpha($wtr_im, true);
  362. if (IMAGE_TYPE_PNG == $wtrSize[2] && imageistruecolor($wtr_im))
  363. $mergeResult = imagecopy ( $dst_im, $wtr_im, $watermarkX, $watermarkY, 0, 0, $wtrSize[0], $wtrSize[1]);
  364. else
  365. $mergeResult = imagecopymerge ( $dst_im, $wtr_im, $watermarkX, $watermarkY, 0, 0, $wtrSize[0], $wtrSize[1], $wtrTransparency );
  366. if ( !$mergeResult )
  367. return IMAGE_ERROR_GD_MERGE_ERROR;
  368. switch ( $size[2] )
  369. {
  370. case IMAGE_TYPE_GIF:
  371. $writeResult = imagegif( $dst_im, $dstFilename );
  372. break;
  373. case IMAGE_TYPE_JPG:
  374. $writeResult = imagejpeg( $dst_im, $dstFilename, $this->_iJpegQuality);
  375. break;
  376. case IMAGE_TYPE_PNG:
  377. $writeResult = imagepng( $dst_im, $dstFilename );
  378. break;
  379. }
  380. // free memory
  381. imagedestroy( $dst_im );
  382. imagedestroy( $src_im );
  383. imagedestroy( $wtr_im );
  384. if ( $writeResult )
  385. return IMAGE_ERROR_SUCCESS;
  386. else
  387. return IMAGE_ERROR_GD_WRITE_FAILED;
  388. }
  389. function _applyWatermarkImageMagick($srcFilename, $dstFilename, $wtrFilename, $wtrTransparency) {
  390. $imgTransparency = 100 - $wtrTransparency;
  391. $cmd = "{$GLOBALS['COMPOSITE']} -gravity \"South\" -dissolve \"$imgTransparency\" \"$wtrFilename\" -dissolve $wtrTransparency \"$srcFilename\" \"$dstFilename\"";
  392. @exec( $cmd );
  393. if ( file_exists($dstFilename) )
  394. return IMAGE_ERROR_SUCCESS;
  395. return IMAGE_ERROR_IMAGEMAGICK_ERROR;
  396. }
  397. function & _createGDImage($s, &$aSize, &$iErr) {
  398. if (!isset($this->gdInfoArray))
  399. $this->gdInfoArray = gd_info();
  400. $aSize = getimagesize($s);
  401. // only GIF, JPG and PNG allowed
  402. switch ( $aSize[2] )
  403. {
  404. case IMAGE_TYPE_GIF:
  405. if (!isset($this->gdInfoArray['GIF Read Support']) || !$this->gdInfoArray['GIF Read Support'] || !isset($this->gdInfoArray['GIF Create Support']) || !$this->gdInfoArray['GIF Create Support'])
  406. return ($iErr = IMAGE_ERROR_GD_TYPE_NOT_SUPPORTED);
  407. $r = imagecreatefromgif( $s );
  408. return $r;
  409. case IMAGE_TYPE_JPG:
  410. if ((!isset($this->gdInfoArray['JPG Support']) || !$this->gdInfoArray['JPG Support']) && (!isset($this->gdInfoArray['JPEG Support']) || !$this->gdInfoArray['JPEG Support']))
  411. return ($iErr = IMAGE_ERROR_GD_TYPE_NOT_SUPPORTED);
  412. $r = imagecreatefromjpeg( $s );
  413. return $r;
  414. case IMAGE_TYPE_PNG:
  415. if (!isset($this->gdInfoArray['PNG Support']) || !$this->gdInfoArray['PNG Support'])
  416. return ($iErr = IMAGE_ERROR_GD_TYPE_NOT_SUPPORTED);
  417. $r = imagecreatefrompng( $s );
  418. return $r;
  419. default:
  420. return ($iErr = IMAGE_ERROR_WRONG_TYPE);
  421. }
  422. }
  423. function _writeImageGD ($src_im, $sDstImage, $iSrcImageType) {
  424. $writeResult = false;
  425. switch ($this->_iForceOutputType){
  426. case IMAGE_TYPE_JPG:
  427. $writeResult = imagejpeg( $src_im, $sDstImage, $this->_iJpegQuality);
  428. break;
  429. case IMAGE_TYPE_PNG:
  430. $writeResult = imagepng( $src_im, $sDstImage);
  431. break;
  432. case IMAGE_TYPE_GIF:
  433. $writeResult = imagegif( $src_im, $sDstImage );
  434. break;
  435. default:
  436. switch ($iSrcImageType) {
  437. case IMAGE_TYPE_GIF:
  438. $writeResult = imagegif( $src_im, $sDstImage );
  439. break;
  440. case IMAGE_TYPE_PNG:
  441. $writeResult = imagepng( $src_im, $sDstImage );
  442. break;
  443. case IMAGE_TYPE_JPG:
  444. default:
  445. $writeResult = imagejpeg( $src_im, $sDstImage, $this->_iJpegQuality);
  446. break;
  447. }
  448. }
  449. return $writeResult;
  450. }
  451. }
  452. /** @} */