1
|
|
|
<?php |
2
|
|
|
class ImageOrientationFixer extends DataExtension { |
3
|
|
|
|
4
|
|
|
public function onBeforeWrite() { |
5
|
|
|
$ext = $this->owner->getExtension(); |
6
|
|
|
if (strtolower($ext) == 'jpg' || strtolower($ext) == 'jpeg') { |
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
|
|
|
$image = imagecreatefromjpeg($path); |
53
|
|
|
|
54
|
|
|
switch ($orientation) { |
55
|
|
|
case 3: |
56
|
|
|
$image = imagerotate($image, 180, 0); |
57
|
|
|
break; |
58
|
|
|
case 6: |
59
|
|
|
$image = imagerotate($image, -90, 0); |
60
|
|
|
break; |
61
|
|
|
case 8: |
62
|
|
|
$image = imagerotate($image, 90, 0); |
63
|
|
|
break; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
imagejpeg($image, $path, 100); |
67
|
|
|
imagedestroy($image); |
68
|
|
|
return true; |
69
|
|
|
} |
70
|
|
|
} |