Library /lib/includes/class.ImageConverter.php

Language PHP Lines 526
MD5 Hash 50da90182394ada499cb32e075e09255
Repository https://github.com/reshadf/Library.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
<?php

/**
 * class ImageConverter
 *
 * Convert images: resize or merge an image
 *
 * @author Teye Heimans
 * @package FormHandler
 */
class ImageConverter
{
	// private vars!
    var $_sImage;
    var $_sError;
    var $_aSize;
    var $_aNewSize;
    var $_iQuality;
    var $_bConstrainProportions;

    /**
     * ImageConverter::ImageConverter()
     *
     * constructor: Create a new ImageConverter object
     *
     * @param string $sImage: The image to work with
     * @return ImageConverter
     * @author Teye Heimans
     * @access public
     */
    function ImageConverter( $sImage )
    {
        $this->_bConstrainProportions = true;
        $this->_sError   = '';
        $this->_sImage   = $sImage;
        $this->_iQuality = 80;

        // does the file exists ?
        if( file_exists($sImage) )
        {
            $this->_aSize     = getimagesize( $sImage );
            $this->_aNewSize  = $this->_aSize;

            // is the type of the image right to convert it ?
            if(!in_array(
              $this->_getExtension( $sImage ) ,
              array('jpg', 'png', 'jpeg', 'gif')))
            {
                $this->_sError = 'Only gif, jpg, jpeg and png files can be converted!';
                return;
            }
        }
        // file does not exitst
        else
        {
            $this->_sError = 'File not found: '.$sImage;
            return;
        }
    }

    /**
     * ImageConverter::setQuality()
     *
     * Set the quality of the new resized image
     *
     * @param int $iQuality: the quality
     * @return void
     * @author Teye Heimans
     * @access public
     */
    function setQuality( $iQuality )
    {
    	if( !empty( $iQuality ) && is_numeric( $iQuality ) )
    	{
        	$this->_iQuality = (int) $iQuality;
    	}
    }

    /**
     * ImageConverter::getError()
     *
     * Return the last error occoured
     *
     * @return string: the last occoured error
     * @author Teye Heimans
     * @access public
     */
    function getError()
    {
    	return isset($this->_sError) ? $this->_sError : '';
    }

    /**
     * ImageConverter::doResize()
     *
     * Resize the image
     *
     * @param string $sDestination: The file how we have to save it
     * @param int $iNewWidth: The new width of the image
     * @param int $iNewHeight: The new height of the image
     * @return void
     * @author Teye Heimans
     * @access public
     */
    function doResize( $sDestination , $iNewWidth, $iNewHeight )
    {
        // if no errors occourd
        if($this->_sError == '')
        {
        	// set the new size
        	$this->_setSize( $iNewWidth, $iNewHeight );

        	// check if the destination dir exists
        	if(!is_dir( dirname( $sDestination ) ))
        	{
        		$this->_sError = 'Destination dir does not exists: '.dirname( $sDestination );
        		return;
        	}

        	// when no filename is given as destination, use the original filename
        	$c = substr($sDestination, -1, 1);
        	if( $c == '/' || $c == '\\' )
        	{
        		$sDestination .= basename( $this->_sImage );
        	}

        	// does the destination has an extension attached ?
        	if( !in_array( $this->_getExtension( $sDestination ), array('jpg', 'jpeg', 'png', 'gif')))
        	{
        		// if not, put the extension of the original file behind it
        		$sDestination .= '.'.$this->_getExtension($this->_sImage);
        	}

        	// get the resource of the original file
            $rOrg = $this->_imageCreate( $this->_sImage );

            // get the old and new sizes of the image
            list($iOrgWidth, $iOrgHeight) = $this->_aSize;
            list($iNewWidth, $iNewHeight) = $this->_aNewSize;

            // generate the new image
            if($this->GDVersion() >= 2)
            {
                $rImgResized = ImageCreateTrueColor( $iNewWidth, $iNewHeight );

                if( $this->_getExtension( $sDestination ) == 'png' )
                {
					imagealphablending($rImgResized, false);
					imagesavealpha($rImgResized, true);
                }

                ImageCopyResampled( $rImgResized, $rOrg, 0, 0, 0, 0, $iNewWidth, $iNewHeight, $iOrgWidth, $iOrgHeight );
            }
            else
            {
                $rImgResized = ImageCreate( $iNewWidth, $iNewHeight );
                ImageCopyResized( $rImgResized, $rOrg, 0, 0, 0, 0, $iNewWidth, $iNewHeight, $iOrgWidth, $iOrgHeight );
            }

            // save the image to file
            $this->_saveImage( $rImgResized, $sDestination, $this->_iQuality );

            // // set the new width of the image if we are overwriting the original file
            if( $sDestination == $this->_sImage )
            {
	            $this->_aSize[0] = $iNewWidth;
	            $this->_aSize[1] = $iNewHeight;
            }

            // clean up
            ImageDestroy( $rOrg );
            ImageDestroy( $rImgResized );
        }
    }

    /**
     * ImageConverter::setConstrainProportions()
     *
     * Should we keep the image proportional when resizing ?
     *
     * @param bool $status
     * @return void
     * @access public
     * @author Teye Heimans
     */
    function setConstrainProportions( $status = true )
    {
        $this->_bConstrainProportions = (bool) $status;
    }

    /**
     * ImageConverter::doMerge()
     *
     * Merge the image with a stamp
     *
     * @param string $sStamp: the stamp image
     * @param string $sAlign: the horizontal alignment of the stamp (give in percentage or as top, center, bottom)
     * @param string $sValign: the vertial alignment of the stamp (give in percentage or as top, middle, bottom)
     * @param array $aTransparant: array of rgb color value which should be transparant
     * @return void
     * @access public
     * @author Teye Heimans
     */
    function doMerge( $sStamp, $sAlign, $sValign, $aTransparant = null )
    {
        if( file_exists($sStamp))
        {
        	if(!function_exists('imagecopyresampled'))
        	{
        		trigger_error(
        		  'Error, the required function imagecopyresampled does not exists! '.
        		  'Could not generate new image.',
        		  E_USER_WARNING
        		);
        		return;
        	}

        	// Open the current file (get the resource )
            $rImgSrc = $this->_imageCreate( $this->_sImage );

            // create the "new" file recourse
            $rImgDest = ImageCreateTrueColor( $this->_aSize[0], $this->_aSize[1] );

            // Open the stamp image
            $rImgStamp = $this->_imageCreate( $sStamp );

            // Transparant color...
            if( is_array($aTransparant) )
            {
            	$color = ImageColorAllocate( $rImgStamp, $aTransparant[0], $aTransparant[1], $aTransparant[2] );
            	ImageColorTransparent($rImgStamp, $color);
            }

            // Copy the current file to the new one
            ImageCopy( $rImgDest, $rImgSrc, 0,0,0,0, $this->_aSize[0], $this->_aSize[1] );
            ImageDestroy( $rImgSrc );

            // get the new position for the stamp
            $x = ImageSX( $rImgStamp );
            $y = ImageSY( $rImgStamp );
            $posX = $this->_getPos( $this->_aSize[0], $x, $sAlign );
            $posY = $this->_getPos( $this->_aSize[1], $y, $sValign );

            // copy the stamp to the new image
            ImageCopyMerge( $rImgDest, $rImgStamp, $posX, $posY, 0, 0, $x, $y, 100 );
            //ImageCopy( $rImgDest, $rImgStamp, $posX, $posY, 0, 0, $x, $y );  # transparant isnt working!
            //ImageCopyResampled( $rImgDest, $rImgStamp, 0, 0, $x, $y, $x, $y ); # transparant isnt working!

            ImageDestroy( $rImgStamp );

            // Save the new image
            $this->_saveImage( $rImgDest, $this->_sImage, 100 );
            ImageDestroy( $rImgDest );
		}
		else
		{
			trigger_error('Error, stamp file does not exists: '. $sStamp, E_USER_WARNING );
		}
    }

    /**
	 * ImageConverter::GDVersion()
	 *
	 * Return the installed GD version
	 *
	 * @param int $user_ver: the version needed by the user
	 * @return int: the installed gd version or 0 on failure
	 * @access public
	 * @author Teye Heimans
	 */
	function GDVersion($user_ver = 0)
	{
	   	if (!extension_loaded('gd'))
	   	{
	   		return false;
	   	}

	   	static $gd_ver = 0;

	   	// Just accept the specified setting if it's 1.
	   	if ($user_ver == 1)
	   	{
	   		$gd_ver = 1;
	   		return 1;
	   	}

	   	// Use the static variable if function was called previously.
	   	if ($user_ver != 2 && $gd_ver > 0 )
	   	{
	   		return $gd_ver;
	   	}

	   	// Use the gd_info() function if possible.
	   	if (function_exists('gd_info'))
	   	{
	   		$ver_info = gd_info();
	       	preg_match('/\d/', $ver_info['GD Version'], $match);
	       	$gd_ver = $match[0];
	       	return $match[0];
	   	}
	   	// If phpinfo() is disabled use a specified / fail-safe choice...
	   	if (preg_match('/phpinfo/', ini_get('disable_functions')))
	   	{
	   		if ($user_ver == 2)
	   		{
	        	$gd_ver = 2;
	           	return 2;
	       	}
	       	else
	       	{
	           	$gd_ver = 1;
	           	return 1;
	       	}
	   	}

		// ...otherwise use phpinfo().
		ob_start();
		phpinfo(8);
		$info = ob_get_contents();
		ob_end_clean();
		$info = stristr($info, 'gd version');
		preg_match('/\d/', $info, $match);
		$gd_ver = $match[0];
		return $match[0];
	}


    /******************************
     *      Private methods       *
     ******************************/


     /**
      * ImageConverter::_setSize()
      *
      * Set the new size of the image and calculate the new size directly
      *
      * @param int $x: the new width
      * @param int $y: the new height
      * @return void
      * @access private
      * @author Teye Heimans
      */
    function _setSize( $x, $y )
    {
        // if no errors occourd
        if($this->_sError == '')
        {
            // calculate the new sizes if we have to contrain the proportions
            if( $this->_bConstrainProportions )
            {
                // get the current sizes
                list( $iWidth, $iHeight ) = $this->_aSize;

                // get the new size
                if( $iWidth > $x )
                  $this->_getNewSize( $iWidth, $iHeight, $x );

                if( $iHeight > $y )
                  $this->_getNewSize( $iHeight, $iWidth, $y );
            }
            // we dont have to contrain the proportions, just use the sizes
            else
            {
                $iWidth  = $x;
                $iHeight = $y;
            }

            $this->_aNewSize = array( $iWidth, $iHeight );
        }
    }


	/**
	 * ImageConverter::_getPos()
	 *
	 * Get the position of the new stamp
	 *
	 * @param int $size: the size of the image (width of height)
	 * @param int $stampSize: the size of the stamp (width of height)
	 * @param string $where: position where to put the stamp on the image
	 * @return int
	 * @access private
	 * @author Teye Heimans
	 */
    function _getPos( $size, $stampSize, $where )
    {
    	// percentage ?
    	if(strpos($where, '%') !== false)
    	{
    		$percent = str_replace( '%', '', $where );
    		$part    = $size / 100;
    		$x       = ceil( $percent * $part );
    	}
    	else
    	{
	        // get the pos for the copyright stamp
	        switch (StrToLower($where))
	        {
	            case 'top':
	            case 'left':
	              $x = 0;
	              break;
	            case 'middle':
	            case 'center':
	              $x = ceil($size / 2) - ceil($stampSize / 2);
	              break;
	            case 'bottom':
	            case 'right':
	              $x = $size - $stampSize;
	              break;
	            default:
	              $x = 0;
	        }
    	}

        return $x;
    }

    /**
     * ImageConverter::_getNewSize()
     *
     * Calculate the new size
     *
     * @param int $x: The old width
     * @param int $y: The old height
     * @param int $max: The max width/height allowed
     * @return void
     * @access private
     * @author Teye Heimans
     */
    function _getNewSize( &$x, &$y, $max )
    {
        $procent = $x / 100;
        $scale   = $max / $procent;
        $x       = $scale * $procent;
        $y       = $scale * ($y / 100);
    }

    /**
     * ImageConverter::_getExtension()
     *
     * Return the extension of the given file
     *
     * @param string $sFile: the file where we have to retrieve the extension from
     * @return string
     * @access private
     * @author Teye Heimans
     */
    function _getExtension( $sFile )
    {
        $fp = explode( '.', $sFile );
        return StrToLower( $fp[ count($fp) -1 ] );
    }

    /**
     * ImageConverter::_imageCreate()
     *
     * Create a new image resource based on the extension of the given file
     *
     * @param string $sFile: The file
     * @return resource or false on failure
     * @author Teye Heimans
     * @access private
     */
    function _imageCreate( $sFile )
    {
        $sExt = $this->_getExtension( $sFile );

        // got extension ?
        if( $sExt )
        {
            if($sExt == 'jpg' || $sExt == 'jpeg')
            {
                return ImageCreateFromJPEG( $sFile );
            }
            elseif($sExt == 'png')
            {
                return ImageCreateFromPNG( $sFile);
            }
            elseif($sExt == 'gif' && function_exists('imagecreatefromgif'))
            {
                return ImageCreateFromGIF( $sFile );
            }
        }

        // something went wrong
        return false;
    }

    /**
     * ImageConverter::_saveImage()
     *
     * Function to save the new image
     *
     * @param resource $rImg: the image to save
     * @param string $sDestination: how to save the new image
     * @param int $iQuality: the quality of the new image
     * @return bool: true of succes and false on failure
     * @access private
     * @author Teye Heimans
     */
    function _saveImage( &$rImage, $sDestination, $iQuality = null )
    {
        $sExt = $this->_getExtension( $sDestination );

        if($sExt == 'jpg' || $sExt == 'jpeg')
        {
            return ImageJPEG($rImage, $sDestination, $iQuality);
        }
        elseif($sExt == 'png')
        {
            return ImagePNG($rImage, $sDestination);
        }
        elseif( $sExt == 'gif' && function_exists('imagegif') )
        {
            return imagegif($rImage, $sDestination);
        }
        else
        {
            trigger_error('Wrong destination given!', E_USER_WARNING );
            return false;
        }
    }
}
?>
Back to Top