1
|
|
|
<?php |
2
|
|
|
class ImageOrientationFixer extends DataExtension { |
3
|
|
|
|
4
|
|
|
public function onBeforeWrite() { |
5
|
|
|
$ext = $this->owner->getExtension(); |
6
|
|
|
if ($ext == 'jpg') { |
7
|
|
|
$path = $this->owner->getFullPath(); |
8
|
|
|
if ($orientation = $this->get_orientation($path)) { |
9
|
|
|
if (extension_loaded('imagick')) { |
10
|
|
|
$this->rotate_imagick($path, $orientation); |
11
|
|
|
} elseif (extension_loaded('gd')) { |
12
|
|
|
$this->rotate_gd($path, $orientation); |
13
|
|
|
} |
14
|
|
|
} |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
parent::onBeforeWrite(); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
private function get_orientation($path) { |
21
|
|
|
$exif_data = exif_read_data($path); |
22
|
|
|
$orientation = !empty($exif_data['Orientation']) ? $exif_data['Orientation'] : null; |
23
|
|
|
/** |
24
|
|
|
* this image will help you understand the orientation and the difference between encoded and printed |
25
|
|
|
* http://www.kendawson.ca/wp-content/uploads/orient_flag2.gif |
26
|
|
|
*/ |
27
|
|
|
return $orientation == 1 ? false : $orientation; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
private function rotate_imagick($imagePath, $orientation) { |
31
|
|
|
$imagick = new Imagick($imagePath); |
32
|
|
|
$imagick->setImageOrientation(imagick::ORIENTATION_TOPLEFT); |
33
|
|
|
$deg = 0; |
34
|
|
|
switch ($orientation) { |
35
|
|
|
case 3: |
36
|
|
|
$deg = -180; |
37
|
|
|
break; |
38
|
|
|
case 6: |
39
|
|
|
$deg = 90; |
40
|
|
|
break; |
41
|
|
|
case 8: |
42
|
|
|
$deg = -90; |
43
|
|
|
break; |
44
|
|
|
} |
45
|
|
|
$imagick->rotateImage(new ImagickPixel('#00000000'), $deg); |
46
|
|
|
$imagick->writeImage($imagePath); |
47
|
|
|
$imagick->clear(); |
48
|
|
|
$imagick->destroy(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private function rotate_gd($path, $orientation) { |
52
|
|
|
$imgInfo = getimagesize($path); |
53
|
|
|
switch ($imgInfo[2]) { |
54
|
|
|
case 1: |
55
|
|
|
$image = imagecreatefromgif($path); |
56
|
|
|
break; |
57
|
|
|
case 2: |
58
|
|
|
$image = imagecreatefromjpeg($path); |
59
|
|
|
break; |
60
|
|
|
case 3: |
61
|
|
|
$image = imagecreatefrompng($path); |
62
|
|
|
break; |
63
|
|
|
default: |
64
|
|
|
return false; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
switch ($orientation) { |
68
|
|
|
case 3: |
69
|
|
|
$image = imagerotate($image, 180, 0); |
70
|
|
|
break; |
71
|
|
|
case 6: |
72
|
|
|
$image = imagerotate($image, -90, 0); |
73
|
|
|
break; |
74
|
|
|
case 8: |
75
|
|
|
$image = imagerotate($image, 90, 0); |
76
|
|
|
break; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
switch ($imgInfo[2]) { |
80
|
|
|
case 1: |
81
|
|
|
imagegif($image, $path); |
82
|
|
|
break; |
83
|
|
|
case 2: |
84
|
|
|
imagejpeg($image, $path, 100); |
85
|
|
|
break; |
86
|
|
|
case 3: |
87
|
|
|
imagepng($image, $path); |
88
|
|
|
break; |
89
|
|
|
default: |
90
|
|
|
imagedestroy($image); |
91
|
|
|
return false; |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
imagedestroy($image); |
95
|
|
|
|
96
|
|
|
return true; |
97
|
|
|
} |
98
|
|
|
} |