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
|
|
|
if (!file_exists($path)) { return false; } |
22
|
|
|
try { |
23
|
|
|
$exif_data = @exif_read_data($path); |
24
|
|
|
$orientation = !empty($exif_data['Orientation']) ? $exif_data['Orientation'] : null; |
25
|
|
|
/** |
26
|
|
|
* this image will help you understand the orientation and the difference between encoded and printed |
27
|
|
|
* http://www.kendawson.ca/wp-content/uploads/orient_flag2.gif |
28
|
|
|
*/ |
29
|
|
|
return $orientation == 1 ? false : $orientation; |
30
|
|
|
} catch (Exception $e) { |
31
|
|
|
return false; |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
private function rotate_imagick($imagePath, $orientation) { |
36
|
|
|
$imagick = new Imagick($imagePath); |
37
|
|
|
$imagick->setImageOrientation(imagick::ORIENTATION_TOPLEFT); |
38
|
|
|
$deg = 0; |
39
|
|
|
switch ($orientation) { |
40
|
|
|
case 3: |
41
|
|
|
$deg = -180; |
42
|
|
|
break; |
43
|
|
|
case 6: |
44
|
|
|
$deg = 90; |
45
|
|
|
break; |
46
|
|
|
case 8: |
47
|
|
|
$deg = -90; |
48
|
|
|
break; |
49
|
|
|
} |
50
|
|
|
$imagick->rotateImage(new ImagickPixel('#00000000'), $deg); |
51
|
|
|
$imagick->writeImage($imagePath); |
52
|
|
|
$imagick->clear(); |
53
|
|
|
$imagick->destroy(); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
private function rotate_gd($path, $orientation) { |
57
|
|
|
$image = imagecreatefromjpeg($path); |
58
|
|
|
|
59
|
|
|
switch ($orientation) { |
60
|
|
|
case 3: |
61
|
|
|
$image = imagerotate($image, 180, 0); |
62
|
|
|
break; |
63
|
|
|
case 6: |
64
|
|
|
$image = imagerotate($image, -90, 0); |
65
|
|
|
break; |
66
|
|
|
case 8: |
67
|
|
|
$image = imagerotate($image, 90, 0); |
68
|
|
|
break; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
imagejpeg($image, $path, 100); |
72
|
|
|
imagedestroy($image); |
73
|
|
|
return true; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|