1
0

BxDolImageResize.php 18 KB

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