php图片处理库

裁剪图片类

主要特色:

可以固定高宽,自定义背景。

 

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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
<?php
class Resize_Image
{
public $fileName = null;
public $imageBackgroundColor = 0;

const POSITION_TOP_LEFT = 'top-left';
const POSITION_TOP_RIGHT = 'top-right';
const POSITION_BOTTOM_LEFT = 'bottom-left';
const POSITION_BOTTOM_RIGHT = 'bottom-right';
const POSITION_STRETCH = 'stretch';
const POSITION_TILE = 'tile';
const POSITION_CENTER = 'center';

protected $_fileType = null;
protected $_fileName = null;
protected $_fileMimeType = null;
protected $_fileSrcName = null;
protected $_fileSrcPath = null;
protected $_imageHandler = null;
protected $_imageSrcWidth = null;
protected $_imageSrcHeight = null;
protected $_watermarkPosition = null;
protected $_watermarkWidth = null;
protected $_watermarkHeigth = null;
protected $_watermarkImageOpacity = null;
protected $_quality = null;

protected $_keepAspectRatio;
protected $_keepFrame;
protected $_keepTransparency;
protected $_backgroundColor;
protected $_constrainOnly;

public function getMimeType()
{
if( $this->_fileType ) {
return $this->_fileType;
} else {
list($this->_imageSrcWidth, $this->_imageSrcHeight, $this->_fileType, ) = getimagesize($this->_fileName);
$this->_fileMimeType = image_type_to_mime_type($this->_fileType);
return $this->_fileMimeType;
}
}

/**
* Retrieve Original Image Width
*
* @return int|null
*/
public function getOriginalWidth()
{
$this->getMimeType();
return $this->_imageSrcWidth;
}

/**
* Retrieve Original Image Height
*
* @return int|null
*/
public function getOriginalHeight()
{
$this->getMimeType();
return $this->_imageSrcHeight;
}

public function setWatermarkPosition($position)
{
$this->_watermarkPosition = $position;
return $this;
}

public function getWatermarkPosition()
{
return $this->_watermarkPosition;
}

public function setWatermarkImageOpacity($imageOpacity)
{
$this->_watermarkImageOpacity = $imageOpacity;
return $this;
}

public function getWatermarkImageOpacity()
{
return $this->_watermarkImageOpacity;
}

public function setWatermarkWidth($width)
{
$this->_watermarkWidth = $width;
return $this;
}

public function getWatermarkWidth()
{
return $this->_watermarkWidth;
}

public function setWatermarkHeigth($heigth)
{
$this->_watermarkHeigth = $heigth;
return $this;
}

public function getWatermarkHeigth()
{
return $this->_watermarkHeigth;
}

/**
* Get/set keepAspectRatio
*
* @param bool $value
* @return bool|Varien_Image_Adapter_Abstract
*/
public function keepAspectRatio($value = null)
{
if (null !== $value) {
$this->_keepAspectRatio = (bool)$value;
}
return $this->_keepAspectRatio;
}

/**
* Get/set keepFrame
*
* @param bool $value
* @return bool
*/
public function keepFrame($value = null)
{
if (null !== $value) {
$this->_keepFrame = (bool)$value;
}
return $this->_keepFrame;
}

/**
* Get/set keepTransparency
*
* @param bool $value
* @return bool
*/
public function keepTransparency($value = null)
{
if (null !== $value) {
$this->_keepTransparency = (bool)$value;
}
return $this->_keepTransparency;
}

/**
* Get/set constrainOnly
*
* @param bool $value
* @return bool
*/
public function constrainOnly($value = null)
{
if (null !== $value) {
$this->_constrainOnly = (bool)$value;
}
return $this->_constrainOnly;
}

/**
* Get/set quality, values in percentage from 0 to 100
*
* @param int $value
* @return int
*/
public function quality($value = null)
{
if (null !== $value) {
$this->_quality = (int)$value;
}
return $this->_quality;
}

/**
* Get/set keepBackgroundColor
*
* @param array $value
* @return array
*/
public function backgroundColor($value = null)
{
if (null !== $value) {
if ((!is_array($value)) || (3 !== count($value))) {
return;
}
foreach ($value as $color) {
if ((!is_integer($color)) || ($color < 0) || ($color > 255)) {
return;
}
}
}
$this->_backgroundColor = $value;
return $this->_backgroundColor;
}

protected function _getFileAttributes()
{
$pathinfo = pathinfo($this->_fileName);

$this->_fileSrcPath = $pathinfo['dirname'];
$this->_fileSrcName = $pathinfo['basename'];
}

protected $_requiredExtensions = Array("gd");
private static $_callbacks = array(
IMAGETYPE_GIF => array('output' => 'imagegif', 'create' => 'imagecreatefromgif'),
IMAGETYPE_JPEG => array('output' => 'imagejpeg', 'create' => 'imagecreatefromjpeg'),
IMAGETYPE_PNG => array('output' => 'imagepng', 'create' => 'imagecreatefrompng'),
IMAGETYPE_XBM => array('output' => 'imagexbm', 'create' => 'imagecreatefromxbm'),
IMAGETYPE_WBMP => array('output' => 'imagewbmp', 'create' => 'imagecreatefromxbm'),
);

/**
* Whether image was resized or not
*
* @var bool
*/
protected $_resized = false;

public function __construct()
{
// Initialize shutdown function
register_shutdown_function(array($this, 'destruct'));
}

/**
* Destroy object image on shutdown
*/
public function destruct()
{
@imagedestroy($this->_imageHandler);
}

/**
* Opens image file.
*
* @param string $filename
* @throws Varien_Exception
*/
public function open($filename)
{

$this->_fileName = $filename;
$this->getMimeType();
$this->_getFileAttributes();
if ($this->_isMemoryLimitReached()) {
throw new Varien_Exception('Memory limit has been reached.');
}
$this->_imageHandler = call_user_func($this->_getCallback('create'), $this->_fileName);
}

/**
* Checks whether memory limit is reached.
*
* @return bool
*/
protected function _isMemoryLimitReached()
{
$limit = $this->_convertToByte(ini_get('memory_limit'));
/**
* In case if memory limit was converted to 0, treat it as unlimited
*/
if ($limit === 0) {
return false;
}
$size = getimagesize($this->_fileName);
$requiredMemory = $size[0] * $size[1] * 3;

return (memory_get_usage(true) + $requiredMemory) > $limit;
}

/**
* Convert PHP memory limit value into bytes
* Notation in value is supported only for PHP
* Shorthand byte options are case insensitive
*
* @param string $memoryValue
*
* @throws Varien_Exception
* @see http://php.net/manual/en/faq.using.php#faq.using.shorthandbytes
*
* @return int
*/
protected function _convertToByte($memoryValue)
{
$memoryValue = trim($memoryValue);
if (empty($memoryValue)) {
return 0;
}
if (preg_match('~^([1-9][0-9]*)[\s]*(k|m|g)b?$~i', $memoryValue, $matches)) {
$option = strtolower($matches[2]);
$memoryValue = $matches[1];
switch ($option) {
case 'g':
$memoryValue *= 1024;
// no break
case 'm':
$memoryValue *= 1024;
// no break
case 'k':
$memoryValue *= 1024;
break;
default:
break;
}
}
$memoryValue = (int)$memoryValue;

return $memoryValue > 0 ? $memoryValue : 0;
}

public function save($destination=null, $newName=null)
{
$fileName = ( !isset($destination) ) ? $this->_fileName : $destination;

if( isset($destination) && isset($newName) ) {
$fileName = $destination . "/" . $newName;
} elseif( isset($destination) && !isset($newName) ) {
$info = pathinfo($destination);
$fileName = $destination;
$destination = $info['dirname'];
} elseif( !isset($destination) && isset($newName) ) {
$fileName = $this->_fileSrcPath . "/" . $newName;
} else {
$fileName = $this->_fileSrcPath . $this->_fileSrcName;
}

$destinationDir = ( isset($destination) ) ? $destination : $this->_fileSrcPath;

if( !is_writable($destinationDir) ) {
try {
$io = new Varien_Io_File();
$io->mkdir($destination);
} catch (Exception $e) {
throw new Exception("Unable to write file into directory '{$destinationDir}'. Access forbidden.");
}
}
if (!$this->_resized) {
// keep alpha transparency
$isAlpha = false;
$isTrueColor = false;
$this->_getTransparency($this->_imageHandler, $this->_fileType, $isAlpha, $isTrueColor);
if ($isAlpha) {
if ($isTrueColor) {
$newImage = imagecreatetruecolor($this->_imageSrcWidth, $this->_imageSrcHeight);
} else {
$newImage = imagecreate($this->_imageSrcWidth, $this->_imageSrcHeight);
}
$this->_fillBackgroundColor($newImage);
imagecopy(
$newImage,
$this->_imageHandler,
0, 0,
0, 0,
$this->_imageSrcWidth, $this->_imageSrcHeight
);
$this->_imageHandler = $newImage;
}
}

$functionParameters = array();
$functionParameters[] = $this->_imageHandler;
$functionParameters[] = $fileName;

// set quality param for JPG file type
if (!is_null($this->quality()) && $this->_fileType == IMAGETYPE_JPEG)
{
$functionParameters[] = $this->quality();
}

// set quality param for PNG file type
if (!is_null($this->quality()) && $this->_fileType == IMAGETYPE_PNG)
{
$quality = round(($this->quality() / 100) * 10);
if ($quality < 1) {
$quality = 1;
} elseif ($quality > 10) {
$quality = 10;
}
$quality = 10 - $quality;
$functionParameters[] = $quality;
}

call_user_func_array($this->_getCallback('output'), $functionParameters);
}

public function display()
{
header("Content-type: ".$this->getMimeType());
call_user_func($this->_getCallback('output'), $this->_imageHandler);
}

/**
* Obtain function name, basing on image type and callback type
*
* @param string $callbackType
* @param int $fileType
* @return string
* @throws Exception
*/
private function _getCallback($callbackType, $fileType = null, $unsupportedText = 'Unsupported image format.')
{
if (null === $fileType) {
$fileType = $this->_fileType;
}
if (empty(self::$_callbacks[$fileType])) {
throw new Exception($unsupportedText);
}
if (empty(self::$_callbacks[$fileType][$callbackType])) {
throw new Exception('Callback not found.');
}
return self::$_callbacks[$fileType][$callbackType];
}

private function _fillBackgroundColor(&$imageResourceTo)
{
// try to keep transparency, if any
if ($this->_keepTransparency) {
$isAlpha = false;
$transparentIndex = $this->_getTransparency($this->_imageHandler, $this->_fileType, $isAlpha);
try {
// fill truecolor png with alpha transparency
if ($isAlpha) {

if (!imagealphablending($imageResourceTo, false)) {
throw new Exception('Failed to set alpha blending for PNG image.');
}
$transparentAlphaColor = imagecolorallocatealpha($imageResourceTo, 0, 0, 0, 127);
if (false === $transparentAlphaColor) {
throw new Exception('Failed to allocate alpha transparency for PNG image.');
}
if (!imagefill($imageResourceTo, 0, 0, $transparentAlphaColor)) {
throw new Exception('Failed to fill PNG image with alpha transparency.');
}
if (!imagesavealpha($imageResourceTo, true)) {
throw new Exception('Failed to save alpha transparency into PNG image.');
}

return $transparentAlphaColor;
}
// fill image with indexed non-alpha transparency
elseif (false !== $transparentIndex) {
$transparentColor = false;
if ($transparentIndex >=0 && $transparentIndex <= imagecolorstotal($this->_imageHandler)) {
list($r, $g, $b) = array_values(imagecolorsforindex($this->_imageHandler, $transparentIndex));
$transparentColor = imagecolorallocate($imageResourceTo, $r, $g, $b);
}
if (false === $transparentColor) {
throw new Exception('Failed to allocate transparent color for image.');
}
if (!imagefill($imageResourceTo, 0, 0, $transparentColor)) {
throw new Exception('Failed to fill image with transparency.');
}
imagecolortransparent($imageResourceTo, $transparentColor);
return $transparentColor;
}
}
catch (Exception $e) {
// fallback to default background color
}
}
list($r, $g, $b) = $this->_backgroundColor;
$color = imagecolorallocate($imageResourceTo, $r, $g, $b);
if (!imagefill($imageResourceTo, 0, 0, $color)) {
throw new Exception("Failed to fill image background with color {$r} {$g} {$b}.");
}

return $color;
}

/**
* Gives true for a PNG with alpha, false otherwise
*
* @param string $fileName
* @return boolean
*/

public function checkAlpha($fileName)
{
return ((ord(file_get_contents($fileName, false, null, 25, 1)) & 6) & 4) == 4;
}

private function _getTransparency($imageResource, $fileType, &$isAlpha = false, &$isTrueColor = false)
{
$isAlpha = false;
$isTrueColor = false;
// assume that transparency is supported by gif/png only
if ((IMAGETYPE_GIF === $fileType) || (IMAGETYPE_PNG === $fileType)) {
// check for specific transparent color
$transparentIndex = imagecolortransparent($imageResource);
if ($transparentIndex >= 0) {
return $transparentIndex;
}
// assume that truecolor PNG has transparency
elseif (IMAGETYPE_PNG === $fileType) {
$isAlpha = $this->checkAlpha($this->_fileName);
$isTrueColor = true;
return $transparentIndex; // -1
}
}
if (IMAGETYPE_JPEG === $fileType) {
$isTrueColor = true;
}
return false;
}

/**
* Change the image size
*
* @param int $frameWidth
* @param int $frameHeight
*/
public function resize($frameWidth = null, $frameHeight = null)
{
if (empty($frameWidth) && empty($frameHeight)) {
throw new Exception('Invalid image dimensions.');
}

// calculate lacking dimension
if (!$this->_keepFrame) {
if (null === $frameWidth) {
$frameWidth = round($frameHeight * ($this->_imageSrcWidth / $this->_imageSrcHeight));
}
elseif (null === $frameHeight) {
$frameHeight = round($frameWidth * ($this->_imageSrcHeight / $this->_imageSrcWidth));
}
}
else {
if (null === $frameWidth) {
$frameWidth = $frameHeight;
}
elseif (null === $frameHeight) {
$frameHeight = $frameWidth;
}
}

// define coordinates of image inside new frame
$srcX = 0;
$srcY = 0;
$dstX = 0;
$dstY = 0;
$dstWidth = $frameWidth;
$dstHeight = $frameHeight;
if ($this->_keepAspectRatio) {
// do not make picture bigger, than it is, if required
if ($this->_constrainOnly) {
if (($frameWidth >= $this->_imageSrcWidth) && ($frameHeight >= $this->_imageSrcHeight)) {
$dstWidth = $this->_imageSrcWidth;
$dstHeight = $this->_imageSrcHeight;
}
}
// keep aspect ratio
if ($this->_imageSrcWidth / $this->_imageSrcHeight >= $frameWidth / $frameHeight) {
$dstHeight = round(($dstWidth / $this->_imageSrcWidth) * $this->_imageSrcHeight);
} else {
$dstWidth = round(($dstHeight / $this->_imageSrcHeight) * $this->_imageSrcWidth);
}
}
// define position in center (TODO: add positions option)
$dstY = round(($frameHeight - $dstHeight) / 2);
$dstX = round(($frameWidth - $dstWidth) / 2);

// get rid of frame (fallback to zero position coordinates)
if (!$this->_keepFrame) {
$frameWidth = $dstWidth;
$frameHeight = $dstHeight;
$dstY = 0;
$dstX = 0;
}

// create new image
$isAlpha = false;
$isTrueColor = false;
$this->_getTransparency($this->_imageHandler, $this->_fileType, $isAlpha, $isTrueColor);
if ($isTrueColor) {
$newImage = imagecreatetruecolor($frameWidth, $frameHeight);
}
else {
$newImage = imagecreate($frameWidth, $frameHeight);
}

// fill new image with required color
$this->_fillBackgroundColor($newImage);

// resample source image and copy it into new frame
imagecopyresampled(
$newImage,
$this->_imageHandler,
$dstX, $dstY,
$srcX, $srcY,
$dstWidth, $dstHeight,
$this->_imageSrcWidth, $this->_imageSrcHeight
);
$this->_imageHandler = $newImage;
$this->refreshImageDimensions();
$this->_resized = true;
}

public function rotate($angle)
{
/*
$isAlpha = false;
$backgroundColor = $this->_getTransparency($this->_imageHandler, $this->_fileType, $isAlpha);
list($r, $g, $b) = $this->_backgroundColor;
if ($isAlpha) {
$backgroundColor = imagecolorallocatealpha($this->_imageHandler, 0, 0, 0, 127);
}
elseif (false === $backgroundColor) {
$backgroundColor = imagecolorallocate($this->_imageHandler, $r, $g, $b);
}
$this->_imageHandler = imagerotate($this->_imageHandler, $angle, $backgroundColor);
//*/
$this->_imageHandler = imagerotate($this->_imageHandler, $angle, $this->imageBackgroundColor);
$this->refreshImageDimensions();
}

public function watermark($watermarkImage, $positionX=0, $positionY=0, $watermarkImageOpacity=30, $repeat=false)
{
list($watermarkSrcWidth, $watermarkSrcHeight, $watermarkFileType, ) = getimagesize($watermarkImage);
$this->_getFileAttributes();
$watermark = call_user_func($this->_getCallback(
'create',
$watermarkFileType,
'Unsupported watermark image format.'
), $watermarkImage);

$merged = false;

if ($this->getWatermarkWidth() &&
$this->getWatermarkHeigth() &&
($this->getWatermarkPosition() != self::POSITION_STRETCH)
) {
$newWatermark = imagecreatetruecolor($this->getWatermarkWidth(), $this->getWatermarkHeigth());
imagealphablending($newWatermark, false);
$col = imagecolorallocate($newWatermark, 255, 255, 255);
imagecolortransparent($newWatermark, $col);
imagefilledrectangle($newWatermark, 0, 0, $this->getWatermarkWidth(), $this->getWatermarkHeigth(), $col);
imagealphablending($newWatermark, true);
imageSaveAlpha($newWatermark, true);
imagecopyresampled(
$newWatermark,
$watermark,
0, 0, 0, 0,
$this->getWatermarkWidth(), $this->getWatermarkHeigth(),
imagesx($watermark), imagesy($watermark)
);
$watermark = $newWatermark;
}

if( $this->getWatermarkPosition() == self::POSITION_TILE ) {
$repeat = true;
} elseif( $this->getWatermarkPosition() == self::POSITION_STRETCH ) {

$newWatermark = imagecreatetruecolor($this->_imageSrcWidth, $this->_imageSrcHeight);
imagealphablending($newWatermark, false);
$col = imagecolorallocate($newWatermark, 255, 255, 255);
imagecolortransparent($newWatermark, $col);
imagefilledrectangle($newWatermark, 0, 0, $this->_imageSrcWidth, $this->_imageSrcHeight, $col);
imagealphablending($newWatermark, true);
imageSaveAlpha($newWatermark, true);
imagecopyresampled(
$newWatermark,
$watermark,
0, 0, 0, 0,
$this->_imageSrcWidth, $this->_imageSrcHeight,
imagesx($watermark), imagesy($watermark)
);
$watermark = $newWatermark;

} elseif( $this->getWatermarkPosition() == self::POSITION_CENTER ) {
$positionX = ($this->_imageSrcWidth/2 - imagesx($watermark)/2);
$positionY = ($this->_imageSrcHeight/2 - imagesy($watermark)/2);
imagecopymerge(
$this->_imageHandler,
$watermark,
$positionX, $positionY,
0, 0,
imagesx($watermark), imagesy($watermark),
$this->getWatermarkImageOpacity()
);
} elseif( $this->getWatermarkPosition() == self::POSITION_TOP_RIGHT ) {
$positionX = ($this->_imageSrcWidth - imagesx($watermark));
imagecopymerge(
$this->_imageHandler,
$watermark,
$positionX, $positionY,
0, 0,
imagesx($watermark), imagesy($watermark),
$this->getWatermarkImageOpacity()
);
} elseif( $this->getWatermarkPosition() == self::POSITION_TOP_LEFT ) {
imagecopymerge(
$this->_imageHandler,
$watermark,
$positionX, $positionY,
0, 0,
imagesx($watermark), imagesy($watermark),
$this->getWatermarkImageOpacity()
);
} elseif( $this->getWatermarkPosition() == self::POSITION_BOTTOM_RIGHT ) {
$positionX = ($this->_imageSrcWidth - imagesx($watermark));
$positionY = ($this->_imageSrcHeight - imagesy($watermark));
imagecopymerge(
$this->_imageHandler,
$watermark,
$positionX, $positionY,
0, 0,
imagesx($watermark), imagesy($watermark),
$this->getWatermarkImageOpacity()
);
} elseif( $this->getWatermarkPosition() == self::POSITION_BOTTOM_LEFT ) {
$positionY = ($this->_imageSrcHeight - imagesy($watermark));
imagecopymerge(
$this->_imageHandler,
$watermark,
$positionX, $positionY,
0, 0,
imagesx($watermark), imagesy($watermark),
$this->getWatermarkImageOpacity()
);
}

if( $repeat === false && $merged === false ) {
imagecopymerge(
$this->_imageHandler,
$watermark,
$positionX, $positionY,
0, 0,
imagesx($watermark), imagesy($watermark),
$this->getWatermarkImageOpacity()
);
} else {
$offsetX = $positionX;
$offsetY = $positionY;
while( $offsetY <= ($this->_imageSrcHeight+imagesy($watermark)) ) {
while( $offsetX <= ($this->_imageSrcWidth+imagesx($watermark)) ) {
imagecopymerge(
$this->_imageHandler,
$watermark,
$offsetX, $offsetY,
0, 0,
imagesx($watermark), imagesy($watermark),
$this->getWatermarkImageOpacity()
);
$offsetX += imagesx($watermark);
}
$offsetX = $positionX;
$offsetY += imagesy($watermark);
}
}

imagedestroy($watermark);
$this->refreshImageDimensions();
}

public function crop($top=0, $left=0, $right=0, $bottom=0)
{
if( $left == 0 && $top == 0 && $right == 0 && $bottom == 0 ) {
return;
}

$newWidth = $this->_imageSrcWidth - $left - $right;
$newHeight = $this->_imageSrcHeight - $top - $bottom;

$canvas = imagecreatetruecolor($newWidth, $newHeight);

if ($this->_fileType == IMAGETYPE_PNG) {
$this->_saveAlpha($canvas);
}

imagecopyresampled(
$canvas,
$this->_imageHandler,
0, 0, $left, $top,
$newWidth, $newHeight,
$newWidth, $newHeight
);

$this->_imageHandler = $canvas;
$this->refreshImageDimensions();
}

public function checkDependencies()
{
foreach( $this->_requiredExtensions as $value ) {
if( !extension_loaded($value) ) {
throw new Exception("Required PHP extension '{$value}' was not loaded.");
}
}
}

private function refreshImageDimensions()
{
$this->_imageSrcWidth = imagesx($this->_imageHandler);
$this->_imageSrcHeight = imagesy($this->_imageHandler);
}

/*
* Fixes saving PNG alpha channel
*/
private function _saveAlpha($imageHandler)
{
$background = imagecolorallocate($imageHandler, 0, 0, 0);
ImageColorTransparent($imageHandler, $background);
imagealphablending($imageHandler, false);
imagesavealpha($imageHandler, true);
}
}

 

用法:

1
2
3
4
5
6
7
8
9
10
11
$width = 250;
$height = 250;
$file_path = 'D114.jpg';
$imageGd = new Resize_Image;
$imageGd->open($file_path);
$imageGd->keepAspectRatio(true);
$imageGd->keepFrame(true);
$imageGd->keepTransparency(true);
$imageGd->backgroundColor(array(255, 255, 255));
$imageGd->resize($width,$height);
$imageGd->save(null,'D114-2.jpg');

 

转换前是(1770x5045):

D114

转换后是(250x250):

D114-2

坚持原创技术分享,您的支持将鼓励我继续创作!